1. Introduce bootstrap, bootstrap-treeview related files;
2. HTML code
<div> <div id="tree" style="color: #999; font-size: 14px;"></div> <div> <button type="button" class="btn btn-success" id="btn-check-all">Check All</button> <button type="button" class="btn btn-danger" id="btn-uncheck-all">Uncheck All</button> </div> <div id="output"></div> </div>
3. JS code
var defaultData = [ { "id": 0, "icon": "talent-icon-folder", "text": "Computer Science", "nodes": [ { "id": 1, "icon": "talent-icon-folder", "text": "Software Engineering", "nodes": [ { "id": 2, "icon": "talent-icon-file", "text": "Graphics" }, { "id": 3, "icon": "talent-icon-file", "text": "Big data operation" } ] }, { "id": 4, "icon": "talent-icon-file", "text": "The Principle of Microcomputer" } ] }, { "id": 5, "icon": "talent-icon-folder", "text": "Civil Engineering", "state": { "checked": true } }, { "id": 6, "icon": "talent-icon-folder", "text": "Marketing" } ]; var $ checkableTree = $ ('# tree'). treeview ( data: defaultData, levels: 3, showIcon: true, showCheckbox: true, showBorder: false, /*multiSelect: true,*/ selectedColor: 'back', selectedBackColor: 'white', expandIcon: 'talent-icon-towards-the-right', collapseIcon: 'talent-icon-down', checkedIcon: 'talent-icon-check', uncheckedIcon: 'talent-icon-checkbox', onNodeChecked: function(event, node) { console.log(node.id); $('#output').prepend('<p>' + node.text + ' was checked</p>'); // parent - a child must have a parent function doCheckedNode(node) { // initialize var thisDiv = $ ('# tree'); var parentNode = thisDiv.treeview('getParent', node); if(parentNode && 0 <= parentNode.nodeId) { console.log(parentNode); // checked thisDiv.treeview('checkNode', [ parentNode, { silent: true } ]); // recurse doCheckedNode(parentNode); } } doCheckedNode(node); }, onNodeUnchecked: function (event, node) { $('#output').prepend('<p>' + node.text + ' was unchecked</p>'); // child - no father and no child function doUnCheckedNode(node) { // initialize var thisDiv = $ ('# tree'); if(node && node.nodes && 0 < node.nodes.length) { var childNodes = node.nodes; for(var i = 0, len = childNodes.length; i < len; i++) { // uncheck thisDiv.treeview('uncheckNode', [ childNodes[i].nodeId, { silent: true } ]); // recurse doUnCheckedNode(childNodes[i]); } } } doUnCheckedNode(node); } }); $('#btn-check-all').on('click', function (e) { $checkableTree.treeview('checkAll', { silent: $('#chk-check-silent').is(':checked') }); }); $('#btn-uncheck-all').on('click', function (e) { $checkableTree.treeview('uncheckAll', { silent: $('#chk-check-silent').is(':checked') }); });
Fourth, the effect