jstree自身的checkbox和选中做得不是很方便,所以我自己在它之上又封装了一下。脚本如下:
/*
**带checkbox的树形控件使用说明
**@url:此url应该返回一个json串,用于生成树
**@id: 将树渲染到页面的某个div上,此div的id
**@checkId:需要默认勾选的数节点id;1.checkId="all",表示勾选所有节点 2.checkId=[1,2]表示勾选id为1,2的节点
**节点的id号由url传入json串中的id决定
*/
function showCheckboxTree(url,id,checkId){
treeid = id;
menuTree = jQuery("#"+id).bind("loaded.jstree",function(e,data){
jQuery("#"+id).jstree("open_all");
jQuery("#"+id).find("li").each(function(){
if(checkId == 'all'){
jQuery("#"+id).jstree("check_node",jQuery(this));
}else if(checkId instanceof Array){
for(var i=0;i<checkId.length;i++){
if(jQuery(this).attr("id") == checkId[i]){
jQuery("#"+id).jstree("check_node",jQuery(this));
}
}
}
});
}).jstree({
"core" : {
"data":{
"url":url,
"dataType":"json",
"cache":false
},
"attr":{
"class":"jstree-checked"
}
},
"types" : {
"default" : {
"valid_children" : ["default","file"]
},
"file" : {
"icon" : "glyphicon glyphicon-file",
"valid_children" : []
}
},
"checkbox" : {
"keep_selected_style" : false,
"real_checkboxes" : true
},
"plugins" : [
"contextmenu", "dnd", "search",
"types", "wholerow","checkbox"
],
"contextmenu":{
"items":{
"create":null,
"rename":null,
"remove":null,
"ccp":null
}
}
});
}
function getCheckboxTreeSelNode(treeid){
var ids = Array();
jQuery("#"+treeid).find("li").each(function(){
var liid = jQuery(this).attr("id");
if(jQuery("#"+liid+">a").hasClass("jstree-clicked") || jQuery("#"+liid+">a>i").hasClass("jstree-undetermined")){
ids.push(liid);
}
});
return ids;
}
使用方式如下:
1.将脚本保存为CheckboxTree.js
2.引入时,先引入jquery,jstree,再引入CheckboxTree.js
3.在页面中写一个div
<div id="configTree" ></div>
4.调用展示checkboxtree的方法:
var treeid = "configTree";
showCheckboxTree("/accountmanage/getMenuData",treeid,menuid);
说明:
/accountmanage/getMenuData这个url应该返回一个json串,类似于:
[{"id":1,"text":"计算机学院",children:[{"id":"2","text":"软件工程"},{"id":"3","text":"计算机科学与技术"}]},{"id":"4","text":"电气学院"}]
用来形成树
treeid则是需要渲染树的div的id
menuid是一个数组,例如[1,2],则表示“计算机学院”与“软件工程”节点的checkbox默认被选中。