循环jstree以搜索节点id的所有出现,然后更改这些节点的类

loop through jstree to search for all occurences of a node id and then change the class of those nodes

本文关键字:节点 然后 jstree 搜索 id 循环      更新时间:2023-09-26

我有以下javascript代码,它更改了jtree中每个选定节点的类(<ins>标记):

   $j("#actionButton1").click(function() {
      $j.each($j("#demo2").jstree("get_selected"), function(index, element) {
      alert($j(element).attr('id'));
      var sub_id = $j(element).attr('id'); //node id is stored in the varialble sub_id
      $j("#"+sub_id+" ins:eq(1)").attr("class","jstree-icon2"); // set class to display new icon
   });//end of selected nodes loop
});

上面的代码工作得很好,除了一件事,如果选定的sub_id存在于树中的多个位置,则显示新图标的类似乎不起作用。

我相信我已经通过jtree循环搜索所有出现的sub_id,然后将新类关联到节点。

任何关于如何做到这一点的提示都是非常欢迎的。

当你使用# id选择器时,它将只返回第一个元素。将sub_id添加到名称或类属性中应该可以帮助您解决问题。正如我在评论中提到的,id属性在页面中应该是唯一的。

如果您希望将类应用于所有匹配元素而不仅仅是第二个元素,则还需要从选择器中删除:eq(1):eq接受基于0的索引

编辑

你的新选择器:

$j("your-element[name='"+sub_id+"' ins").attr("class","jstree-icon2");

尝试直接引用节点,而不是使用ID作为选择器:

$j('#actionButton1').click(function() {
    $j.each($j('#demo2').jstree('get_selected'), function(index, element) {
        $j('ins:eq(1)', element).addClass('jstree-icon2');
    });
});

如上所述,id应该是唯一的。

我希望这对你有帮助!