1.项目环境
想要将显示区域作为查询的条件,而区域是树形结构并且可以多选,并且数据量很大,是从中国到乡镇的地区数据,如果我们一次将所有的区域数据查出直接塞到树形结构,那么页面将会卡死,因此我们需要每次加载部分数据,如果展开下级,那么显示下一级所有的区域,这样可以解决数据量大而导致页面无法缓存的问题。
2.导入样式表
<link type="text/css" rel="stylesheet" href="../js/jsTree/themes/default/style.min.css">
3.导入js包
<!-- jquery的js包 -->
<script type="text/javascript" src="../js/jquery.min.js"></script>
<!-- jsTree树形结构插件-->
<script type="text/javascript" src="../js/jsTree/jstree.min.js"></script>
4.html
<div id="regionTree" style="margin-left:20px;"></div>
5.区域树
function initRegionTree(){
$("#regionTree").jstree({
'plugins' : ["checkbox"], //出现选择框
'checkbox': { cascade: "", three_state: false }, //不级联
'core': {
"data" : {
"dataType" : 'json',
"opts":{
method: "POST"
},
"url" : function(node){
return url;
},
"data" : function(node){
if(node.id !="#"){
return {"id" : node.id};
}
return {"id" : 0};//写自己的加载数据
}
},
"themes": {
"theme" : "apple",
},
"multiple" : true,//可以多选
}
});
//隐藏图标
$("#regionTree").jstree().hide_icons();
//刷新区域树
$("#regionTree").jstree('refresh');
}
6.页面接收节点的数据结构
[
{"children":false,"id":"107712","text":"广东省"},
{"children":false,"id":"175820","text":"海南省"},
{"children":true,"id":"18047","text":"浙江省"},
{"children":true,"id":"2","text":"福建省"},
{"children":true,"id":"237641","text":"河南省"},
{"children":false,"id":"291426","text":"黑龙江省"},
{"children":true,"id":"307715","text":"湖北省"},
{"children":true,"id":"403889","text":"江苏省"},
{"children":true,"id":"493130","text":"山东省"},
{"children":true,"id":"74873","text":"北京市"},
{"children":true,"id":"81714","text":"安徽省"}
]
分析:
id为标识。
text为显示的文本数据。
children标志位如果为true,那么说明存在子节点,下次点击会自动再次发送链接加载子节点。标志位为false,那么说明当前节点为叶子节点,那么当前节点不存在子节点了。
7.结果
8.获取选中对象的ID和值
var selectedRegionArr = $('#regionTree').jstree().get_checked(true);//获取选中的对象,返回值为数组
for(var i=0 ; i<selectedRegionArr.length ; i++){
alert(selectedRegionArr[i].text);//打印选中的值
alert(selectedRegionArr[i].id);//打印选中的ID
}
9.复选框树通用模型
/**
* 通用方法,生成树模型
* 参数:
* elementId :生成树显示的控件ID
* url:动态加载子节点的url
* initialId:初始化节点
* */
function initJSTree(elementId,url,initialId){
$("#"+elementId).jstree({
'plugins' : ["checkbox"], //出现选择框
'checkbox': { cascade: "", three_state: false }, //不级联
'core': {
"data" : {
"dataType" : 'json',
"opts":{
method: "POST"
},
"url" : function(node){
return url;
},
"data" : function(node){
if(node.id !="#"){
return {"id" : node.id};
}
return {"id" : initialId};
}
},
"themes": {
"theme" : "apple",
},
"multiple" : true,//可以多选
}
});
//隐藏图标
$("#"+elementId).jstree().hide_icons();
//刷新区域树
$("#"+elementId).jstree('refresh');
}
10.jsTree中文API文档