bootstrap插件treeview实现全选父节点下所有子节点和反选功能
程序员文章站
2023-09-06 19:06:44
项目需要实现权限管理,使用前端框架bootstrap,所以就直接选用了bootstrap的treeview扩展插件。先上图:
选中父节点时,父节点下所有子节点也都全部...
项目需要实现权限管理,使用前端框架bootstrap,所以就直接选用了bootstrap的treeview扩展插件。先上图:
选中父节点时,父节点下所有子节点也都全部选中,看代码
1、html代码
<h2>treeview checkable</h2> <div id="treeview-checkable"></div>
2、json数据
function gettvstatedata() { var defaultdata = [ { text: 'parent 1', href: '#parent1', tags: ['4'], state: { checked: true }, nodes: [ { text: 'child 1', href: '#child1', tags: ['2'], nodes: [ { text: 'grandchild 1', href: '#grandchild1', tags: ['0'] }, { text: 'grandchild 2', href: '#grandchild2', tags: ['0'] } ] }, { text: 'child 2', href: '#child2', tags: ['0'] } ] }, { text: 'parent 2', href: '#parent2', tags: ['0'], nodes: [ { text: 'child 1', href: '#child1', tags: ['2'], nodes: [ { text: 'grandchild 1', href: '#grandchild1', tags: ['0'] }, { text: 'grandchild 2', href: '#grandchild2', tags: ['0'] } ] }, { text: 'child 2', href: '#child2', tags: ['0'] } ] }, { text: 'parent 3', href: '#parent3' }, { text: 'parent 4', href: '#parent4', tags: ['0'] }, { text: 'parent 5', href: '#parent5', tags: ['0'] } ]; return defaultdata; }
3、js数据绑定,加载treeview
$(function() { var $checkabletree = $('#treeview-checkable') .treeview({ data: gettvstatedata(), //数据 showicon: false, showcheckbox: true, levels: 1, onnodechecked: function(event, node) { //选中节点 var selectnodes = getchildnodeidarr(node); //获取所有子节点 if (selectnodes) { //子节点不为空,则选中所有子节点 $('#treeview-checkable').treeview('checknode', [selectnodes, { silent: true }]); } var parentnode = $("#treeview-checkable").treeview("getnode", node.parentid); setparentnodecheck(node); }, onnodeunchecked: function(event, node) { //取消选中节点 var selectnodes = getchildnodeidarr(node); //获取所有子节点 if (selectnodes) { //子节点不为空,则取消选中所有子节点 $('#treeview-checkable').treeview('unchecknode', [selectnodes, { silent: true }]); } }, onnodeexpanded: function(event, data) { if (data.nodes === undefined || data.nodes === null) { } else if (data.tags[0] === "2") { alert("tags 2"); } else { alert("1111"); } } }); });
4、选中/取消选中父节点时,选中/取消选中所有子节点,以及选中所有子节点时,选中父节点
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) { var parentnode = $("#treeview-checkable").treeview("getnode", node.parentid); if (parentnode.nodes) { var checkedcount = 0; for (x in parentnode.nodes) { if (parentnode.nodes[x].state.checked) { checkedcount ++; } else { break; } } if (checkedcount === parentnode.nodes.length) { $("#treeview-checkable").treeview("checknode", parentnode.nodeid); setparentnodecheck(parentnode); } } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。