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

我有以下javascript代码更改jstree中每个选定节点的类( 标签):

  $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存在于树中的多个位置,则显示新图标的类似乎不起作用。

我相信我已遍历jstree来搜索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应该是唯一的。

我希望这有帮助!