【问题标题】:How to select every node that holds the same ID如何选择每个拥有相同 ID 的节点
【发布时间】:2010-06-01 07:39:50
【问题描述】:

我有一个 Jstree,其中包含很多节点,其中一些具有相同的 ID。

我想知道,如果有人选择
,我该怎么做 其中一个节点,它将选择具有相同 id 的每个节点。

我尝试过使用

    onselect: function (node) {

但我不确定该怎么做,
另外我不确定如何手动选择节点
(因为都是用 selected: 属性完成的)

【问题讨论】:

标签: jquery jstree


【解决方案1】:

IDs must be unique within the document,所以我假设您需要这样做,因为您从某个地方获取数据并且需要清理它。如果可以,请解决问题的根源。

如果你不能,你可以循环遍历树中的元素来寻找匹配的 ID;像这样:

var theTargetID = /* ...whatever ID you're looking for... */;
$(theTree).find("*").each(function(element) {
    if (this.id == theTargetID) {
        // it matches the ID
    }
});

这将创建一个可能很大的临时数组(匹配树的 所有 个后代元素)。这可能是你最好使用无聊的老式 DOM 遍历而不是 jQuery 的漂亮包装器的地方,因为你试图用无效的文档结构(多个 ID)做一些事情。

寻找目标 ID 的原始 DOM 遍历可能如下所示:

function traverse(theTargetID, element) {
    var node;

    if (element.id == theTargetID) {
        // It matches, do something about it
    }

    // Process child nodes
    for (node = element.firstChild; node; node = node.nextSibling) {
        if (node.nodeType === 1) {  // 1 == Element
            traverse(theTargetID, node);
        }
    }
}

假设element 参数实际上是一个DOM 元素(不是jQuery 对象,或文本节点等)。它检查元素的id,然后在必要时递归处理其子元素。这样可以避免创建一个可能很大的数组。

请注意,我指的是树节点,而不是其中的叶子。您希望在加载树时执行此操作一次,而不仅仅是在选择树中的节点时——因为您希望尽可能短暂地获得无效结构并主动修复它。

【讨论】:

  • 一些好主意,但如果重复的 id 存在于节点的祖先节点上怎么办?
  • @Erik:我会更新它,我假设 OP 用node 指代树的节点,但我怀疑我弄错了。谢谢。
【解决方案2】:

T.J Crowder 已经说过,ID 在文档中必须是唯一的。我认为如果存在重复的 ID,您的 jsTree 中可能会出现非常奇怪的效果,因此我建议您执行以下操作。

对于您单击的每个节点,在下面的示例中将 id 属性的值存储在 var nodeId 中。示例代码将为您找到 var nodeId 的重复项。如果发现重复项,则除了第一个找到的节点之外的所有节点都应将 id 更改为唯一 id。您可以通过将 i 的值或随机文本字符串附加到 id 来做到这一点。

这就是我现在能为你做的一切。如果您能向我们提供一些更详细的信息(HTML 和您当前的 Javascript 代码)会有所帮助。

var nodeId = 'the-node-id'; // The id of your node id here.
$('#' + nodeId).each(function() {
  var matchingIds = $('[id='+this.id+']'); // May find duplicate ids.
  if (matchingIds.length > 1 && matchingIds[0] == this) {
    // Duplicates found.
    for (i = 0; i < matchingIds.length; i++) {
      // Whatever you like to do with the duplicates goes here. I suggest you give them new unique ids.
    }
  }
});

更新:这是一种替代解决方案,在页面加载后直接找到重复的 id,类似于 T.J Crowder 的建议。

$('[id]').each(function() { // Selects all elements with ids in the document.
  var matchingIds = $('[id='+this.id+']'); // May find duplicate ids.
  if (matchingIds.length > 1 && matchingIds[0] == this) {
    // Duplicates found.
    for (i = 0; i < matchingIds.length; i++) {
      // Whatever you like to do with the duplicates goes here. I suggest you give them new unique ids.
    }
  }
});

【讨论】:

    猜你喜欢
    • 2011-11-09
    • 1970-01-01
    • 2021-11-03
    • 2020-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多