如何选择具有相同ID的每个节点

时间:2010-06-01 07:39:51

标签: jquery jstree

我有一个拥有大量节点的Jstree,其中一些节点具有相同的ID。

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

我尝试使用

    onselect: function (node) {

但我不确定究竟要做什么,
加上我不知道如何手动选择节点 (因为它全部使用selected:属性完成)

2 个答案:

答案 0 :(得分:3)

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,然后在必要时递归处理它的子节点。这可以避免创建一个可能很大的数组。

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

答案 1 :(得分:0)

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.
    }
  }
});