jstree学习

function getMenuIds(){  
   
//取得所有选中的节点,返回节点对象的集合
      var ids="";
      var nodes=$("#JsTree").jstree("get_checked"); //使用get_checked方法
      $.each(nodes, function(i, n) {
      ids += $(n).attr("id")+",";
      });
      alert(ids);

}


<script type=”text/javascript”>
$(function(){
var checkNodeIds = “11″.split(“,”);//需要选中的节点ID,为数组

$(“#JsTree”).bind(‘loaded.jstree’, function (e, data) {
$(“#JsTree”).jstree(“open_all”);
$(“#JsTree”).find(“li”).each(function() {
for (var i = 0; i < checkNodeIds.length; i++) {
if ($(this).attr(“id”) == checkNodeIds[i]) { //如果节点的ID等于checkNodeIds[i],表示要选中
//alert($(this).attr(“id”));
$(“#roleTree”).jstree(“check_node”, $(this));
break;
}
}
});
}).jstree({
“themes” : {
“theme” : “default”
},
“plugins” : ["themes", "html_data", "checkbox", "ui"]
});

});

//获取选中的节点ID
function checkForm(obj) {
var ids = checkForm2(obj);
alert(ids);
}
function checkForm2(obj) {
var ids =[];
$.jstree._reference($(“#roleTree”)).get_checked(obj).each(function(i, n) {
ids.push(n.id);
if ($(this).find(“> ul”).length > 0) {
ids.push(checkForm2($(this)));
ids.push(checkForm2($(this)));
}
});
return ids;
}
</script>


<div id=”JsTree” style=”text-align:left; background-color:#FFFFFF;”>
<ul>
<li id=”1″><a href=”#”>系统管理ID1</a>
<ul>
<li id=”11″><a href=”#”>系统管理ID11</a>
<ul>
<li id=”111″><a href=”#”>系统管理ID111</a></li>
<li id=”112″><a href=”#”>系统管理ID112</a></li>
</ul>
</li>
<li id=”12″><a href=”#”>系统管理ID12</a></li>
</ul>
</li>
<li id=”2″><a href=”#”>用户管理ID2</a>
<ul>
<li id=”21″><a href=”#”>普通用户ID21</a></li>
<li id=”22″><a href=”#”>特殊用户ID22</a></li>
</ul>
</li>
</ul>
</div>

为了同时获取半选中状态的节点ID,我们需要修改jquery.jstree.js,打开源文件,直接搜索get_checked或者定位到2319行,可以看到下面代码:


get_checked : function (obj) {
obj = !obj || obj === -1 ? this.get_container() : this._get_node(obj);
return obj.find(“> ul > .jstree-checked, .jstree-undetermined > ul > .jstree-checked”);
}

在return语句中,只返回了具有jstree-checked这个class的节点,即对于半选中状态(即class为jstree-undetermined)的节点并未返回。所以只需要将return语句修改为下面代码即可。


return obj.find(“> ul > .jstree-checked, > ul > .jstree-undetermined”);

具体效果可以见DEMO。

代码中,在tree上绑定loaded.jstree事件,当tree加载成功后,先将tree的所有节点都展开,并根据checkNodeIds来设置tree的节点的选中状态,checkNodeIds中即我们需要选中的节点的ID。

你可能感兴趣的:(jstree)