在使用bootstrap-treeview插件的时候,需要实现选中某个节点时同时选中其祖辈节点和其子孙节点,难受的是它貌似并没有实现这样的功能,只能自己动手实现了,我这里是直接修改源代码实现的。
- 添加选中父辈节点、子孙节点的处理函数
Tree.prototype.setCheckedChildrenState = function(node, state, options) {
//选中后子孙节点
this.setCheckedState(node, state, options);
if(node.nodes != null && node.nodes.length > 0) {
for(var i = 0; i < node.nodes.length; i++) {
this.setCheckedChildrenState(node.nodes[i], node.state.checked, options);
}
}
};
Tree.prototype.setCheckedParentState = function(node, state, options) {
this.setCheckedState(node, state, options);
//选中祖辈节点
if(node.parentId != undefined) {
var parent_ = this.nodes[node.parentId];
this.setCheckedState(parent_, state, options);
}
};
- 找到函数
Tree.prototype.toggleCheckedState = function(node, options) {
if (!node) return;
this.setCheckedState(node, !node.state.checked, options);
}
- 替换 this.setCheckedState(node, !node.state.checked, options);
this.setCheckedChildrenState(node, !node.state.checked, options);
if(node.state.checked) {
this.setCheckedParentState(node, node.state.checked, options);
}
即可完成选择回溯选择祖辈节点和子孙节点。
这里有个疑问就是我们改变某个节点时会把所有的子节点也做对应的改变,回溯祖辈节点的时候,又不会把对应的子节点做相应的改变,似乎存在矛盾。
最后附上修改后的js文件(https://download.csdn.net/download/u014420690/11135605)
我的个人博客目前已经上线,欢迎大家访问http://blog.timefluid.cn