bootsraps treeview选中子节点自动选中父节点及反选
效果图:
引入外部JS及CSS文件:
<link href="${root!}/resource/css/bootstrap.min.css" rel="stylesheet">
<script src="${root!}/resource/js/jquery.min.js?v=2.1.4"></script>
<script src="${root!}/resource/js/bootstrap.min.js?v=3.3.6"></script>
<script src="${root!}/resource/js/plugins/treeview/bootstrap-treeview.js"></script>
2.html容器部分:
<div id="treeview"></div>
3.JS加载数据:
$(function() {
$(".btn").click(function(){
var node = '';
var nodes = $('#treeview').treeview('getSelected');
for (var key in nodes) {
//console.log(nodes[key].F_URI);
node += nodes[key].F_URI + ',';
}
$("#role").val(node);
});
$.getJSON('${root!}/admin/auth/action/tree',
function(data) {
$("#treeview").treeview({
data: data,
selectedIcon: "fa fa-check-square-o",
nodeIcon:"fa fa-square-o",
uncheckedIcon:"fa fa-square-o",
selectable: true,
multiSelect: true , //是否多选
onNodeSelected: function (event,node) {
var selectNodes = getChildNodeIdArr(node); //获取所有子节点
if (selectNodes) { //子节点不为空,则选中所有子节点
$("#treeview").treeview('selectNode', [selectNodes, { silent: true }]);
}
setParentNodeCheck(node,'1');//自动选择父节点
},
onNodeUnselected: function (event, node) {
var selectNodes = getChildNodeIdArr(node); //获取所有子节点
if (selectNodes) { //子节点不为空,则选中所有子节点
$("#treeview").treeview('unselectNode', [selectNodes, { silent: true }]);
}
}
});
});
});
function getChildNodeIdArr(node) {
var ts = [];
if (node.nodes) {
for (x in node.nodes) {
ts.push(node.nodes[x].nodeId);
if (node.nodes[x].nodes) {
var getNodeDieDai = getChildNodeIdArr(node.nodes[x]);
for (j in getNodeDieDai) {
ts.push(getNodeDieDai[j]);
}
}
}
} else {
ts.push(node.nodeId);
}
return ts;
}
function setParentNodeCheck(node,type) {
var parentNode = $("#treeview").treeview("getParent", node);
if (parentNode.nodes) {
if(type=='1'){
$("#treeview").treeview('selectNode', [ parentNode, { silent: true } ]);
setParentNodeCheck(parentNode,'1');
}else{//没用
$("#treeview").treeview('unselectNode', [ parentNode, { silent: true } ]);
setParentNodeCheck(parentNode,'2');
}
}
}
本文原创,转载必追究版权。