jstree获取所选节点的级别

时间:2012-12-17 04:45:15

标签: jquery jstree

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

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

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

3 个答案:

答案 0 :(得分: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
  });

答案 1 :(得分: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>
&#13;
&#13;
&#13;

答案 2 :(得分:2)

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}