4

如何获取当前选定节点的度数/级别?即它有多少父母。

我有在选择节点时执行的部分:

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

3 回答 3

8

您还可以使用(在 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
  });
于 2015-04-01T13:34:42.537 回答
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>

于 2012-12-17T05:32:03.307 回答
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);
})
;
于 2015-04-23T14:56:56.717 回答