繁体   English   中英

如何在jsTree中获取所选节点的ID?

[英]How do I get the id of the selected node in jsTree?

如何在jsTree中获取所选节点的id?

function createNewNode() {
  alert('test');
  var tree = $.tree.reference("#basic_html");
  selectedNodeId = xxxxxxxxx; //insert instruction to get id here
  tree.create({ data : "New Node Name" }, selectedNodeId);
}

由于无法使用harpo的解决方案,并且不愿意使用Olivier的解决方案,因为它使用内部的jsTree函数,我提出了一种不同的方法。

$('#tree').jstree('get_selected').attr('id')

就这么简单。 get_selected函数返回所选列表项的数组。 如果你对该数组执行.attr ,jQuery将查看列表中的第一项。 如果您需要多个选择的ID,请将其视为数组。

jsTree中的节点基本上是包装列表项。 这将为您提供第一个参考。

var n = $.tree.focused().get_node('li:eq(0)')

如果您有对树的引用,则可以替换$.tree.focused()

要获取id,请使用第一个匹配的元素

if (n.length)
    id = n[0].id

或者您可以使用jQuery attr函数,该函数适用于集合中的第一个元素

id = n.attr('id');

jstree 3.1.1版中,您可以直接从get_selected获取它:

$("#<your tree container's id>").jstree("get_selected")

在最新版本的jsTree(在3.3.3中检查)中,您可以执行此操作以获取ID数组:

var ids = $('#tree').jstree('get_selected');

这将返回,例如, ["selected_id1", "selected_id2", "selected_id3"] 如果要获取所选节点 (而不是ID),可以执行以下操作:

var nodes = $('#tree').jstree('get_selected', true);

当前的文档包含更多信息。

  $.jstree._reference('#my_tree_container')._get_node(null, true).each(function() {
    id = $(this).attr("id");
    alert('Id selected: ' + id);        
  });

我在使用MULTIPLE选择从树中获取所选id时遇到问题。 这是我得到它们的方式:

var checked_ids = [];
$("#your-tree-id").jstree('get_selected').each(function(){    
      checked_ids.push($(this).data('id'));                         
});

就我而言,数据调用不起作用。 我成功通过使用attr函数访问我的节点数据。

$("#tree").jstree("get_selected").attr("my-data-name");

获取所有选定的ID使用以下代码

var selectedData = [];
var selectedIndexes;
 selectedIndexes = $("#jstree").jstree("get_selected", true);
jQuery.each(selectedIndexes, function (index, value) {
     selectedData.push(selectedIndexes[index].id);
 });

现在,您在“selectedData”变量中拥有所有选定的ID

随着最新版本的Jstree; 你可以这样做:

<script type="text/javascript>
    var checked_ids = [];
    $('#your-tree-id).jstree("get_checked",null,true).each(function(){
        checked_ids.push(this.id);
    });
    alert(checked_ids.join(","));
</script>
<script type="text/javascript>
    checked_ids.push($(this).context.id);
</script>

只是用

var nodeId = $('#FaqTreeView').jstree().get_selected("id")[0].id;

其中#FaqTreeView是包含jstree的div的id。

在某些情况下和/或jstree版本中,此解决方案不起作用。

$('#tree').jstree('get_selected').attr('id');

而不是定义“id”我没有得到什么。 对我来说诀窍是:

$("#tree").jstree("get_selected").toString();

这些都是旧版本的旧答案。 从版本3.3.3开始,这将获得所选节点的所有属性。

$('#jstree').jstree().get_selected(true)[0]

如果你想要id,那么最后添加.id。 如果复制上述代码,则可以查看Web开发人员工具中的所有其他属性。

您可以使用以下代码var nodes = $(“#jstree_demo_div”)。jstree(true).get_selected(“full”,true); //所选节点的列表

nodes [0] .id //这将从数组中提供第一个对象的id

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM