[英]multi-select tree using javascript object
我想使用Java腳本對象創建帶有復選框的樹,數據采用以下格式,格式如下
<id, name, parent_id>
例如:
1 A -1
2 B 1
3 C 2
4 d 2
5 e 2
parent_id
是一個“ id”,它引用具有該特定“ id”的父對象
我對此有一個裂縫,這就是我的想法。 我注釋了所有代碼,以便您可以遵循邏輯。 希望這可以幫助您學習。
var data = [{ label: "3138 | Root Organization | -1", selected: true, value: "3138" }, { label: "3140 | Company X | 3138", selected: false, value: "3140" }, { label: "3148 | Corporate | 3140", selected: false, value: "3148" }]; var nodes = {}, tree = []; // construct the map of nodes and the tree structure // by looping over the data data.forEach(function(d) { // split the label based on <spaces>|<spaces> and // create a node object with the relevant properties var parts = d.label.split(/\\s+\\|\\s+/), node = { id: parts[0], name: parts[1], parentId: parts[2], children: [] }, parentNode; // if there is no parent, this must be a top level // node, so add it to our tree array. if (node.parentId === "-1") { tree.push(node); } else { // otherwise, the parent must be an existing node // so just add this node to its children parentNode = nodes[node.parentId]; if (parentNode) { parentNode.children.push(node); } } // store this node in the map by id so we can // look it up easily nodes[node.id] = node; }); // the function that recursively draws the tree // params: // element: (string|DOMElement|jQuery) the element to // append the tree to // tree: (node[]) the array of nodes to draw // at the current level function drawTree(element, tree) { var $ul = $('<ul>'); tree.forEach(function(node) { var $li = $('<li>'); $li.text(node.name); // if this node has children, draw them inside // the current <li> if (node.children.length !== 0) { drawTree($li, node.children); } $ul.append($li); }); $ul.appendTo(element); } // invoke the function with the tree data drawTree('#out', tree);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="out"></div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.