jstree获取所选节点的级别

问题描述 投票:4回答:3

如何获得当前所选节点的学位/级别?即它拥有的父母数量。

我有一节在选择节点时执行:

.bind("select_node.jstree", function (event, data) { 
        var nodeInfo = $("#" + data.rslt.obj.attr("id"));
        console.log(data.rslt.obj.attr("id")); // the id of the node
        console.log(nodeInfo.children("a").text()); // the name of the node
                    // the level of the node???
});
jquery jstree
3个回答
5
投票

data.inst.get_path().length

1是根节点;

.bind("select_node.jstree",function(e,data) {
      var inst=data.inst;
      var level=inst.get_path().length;
      var selected=inst.get_selected();
      var id=selected.attr('id');
      var name=selected.prop('tagName');
      console.log(name,id,level);
  });

(最好使用inst,而不是用dom搜索);

$(function () {
	$("#demo1").jstree({ 
		"plugins" : [ "themes", "html_data", "ui", "cookies" ]
	});
	$("#demo2").jstree({ 
		"plugins" : [ "themes", "html_data", "ui", "cookies" ]
	});
  $('#demo1,#demo2').bind("select_node.jstree",function(e,data) {
      var inst=data.inst;
      var level=inst.get_path().length;
      var selected=inst.get_selected();
      var id=selected.attr('id');
      var name=selected.prop('tagName');
      console.log(name,id,level);
  });
    
});
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.2.1/themes/default/style.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.2.1/jstree.min.js"></script>
  With id-s:
<div id="demo1" class="demo">
	<ul>
		<li id="phtml_1">
			<a href="#">Root node 1</a>
			<ul>
				<li id="phtml_2">
					<a href="#">Child node 1</a>

				</li>
				<li id="phtml_3">
					<a href="#">Child node 2</a>
				</li>
			</ul>
		</li>
		<li id="phtml_4">
			<a href="#">Root node 2</a>

		</li>
	</ul>
</div>
  Without id-s:
<div id="demo2" class="demo">
	<ul>
		<li>
			<a href="#">Root node 1</a>
			<ul>
				<li>
					<a href="#">Child node 1</a>                   

				</li>
				<li>
					<a href="#">Child node 2</a>
				</li>
			</ul>
		</li>
		<li>
			<a href="#">Root node 2</a>

		</li>
	</ul>
</div>

7
投票

你也可以使用(在jstree 3.1.0中):

.bind("select_node.jstree",function(e,data) {
      var level=data.node.parents.length;     // 1 = root level, 2 = next level down, etc
  });

2
投票
.bind("select_node.jstree", function(e, data) {
    var level = data.node.parents.length;
    var text  = data.node.text;
    var id    = data.node.id;
    console.log(level,text,id);
})
;
© www.soinside.com 2019 - 2024. All rights reserved.