1. 程式人生 > >js遞迴獲取某個父節點下面的所有子節點

js遞迴獲取某個父節點下面的所有子節點

本次的工作主要是計算節點橙色部分標記的子節點數量,沒有橙色部分的節點,只是隱藏了橙色部分

json資料格式類似這種:

{
    "name": "aaa",
    "Children": [
        {
            "name": "aaa",
            "Children": [
                {
                    "name": "ccc",
                    "Children": [
                        {
                            "name": "ccc",
                            "Children": []
                        }
                    ]
                },
                {
                    "name": "eee",
                    "Children": []
                }
            ]
        }
    ]
}

實現程式碼:

計算節點數:

	function getLeafCountTree(data, level) {

		if (data.Children.length == 0) {
			data.colspan = 1;
			return 1;
		} else {
			var leafCount = 0;
			for (var i = 0; i < data.Children.length; i++) {
				leafCount = leafCount + getLeafCountTree(data.Children[i]);
			}
			data.colspan = leafCount;
			if (data.EmpLevel == "Special" || data.EmpLevel == "Hidename") {//特殊節點不計算在內
				return leafCount;
			} else {
				return leafCount + 1;
			}

		}
	}

建立節點,顯示

function createNode(nodeData, level, opts) {
		var dtd = $.Deferred();
		getLeafCountTree(nodeData);
		var childNodesLength = getLeafCountTree(nodeData);
		// construct the content of node
		var $nodeDiv = $('<div' + (opts.draggable ? ' draggable="true"' : '') + (nodeData[opts.nodeId] ? ' id="' + nodeData[opts.nodeId] + '"' : '') + '>')
			.addClass('node ' + (nodeData.EmpLevel || '') + (level >= opts.depth ? ' slide-up' : ''))
			.append('<div class="title">' + nodeData[opts.nodeTitle] + '(' + childNodesLength + ')' + '</div>').append('<div class="name">' + nodeData[opts.nodeName] + '</div>')
			.append(typeof opts.nodeContent !== 'undefined' ? "<div class=content>" + (nodeData[opts.nodeEmpInfo] || '') + "<br>" + (nodeData[opts.nodeContent] || '') + "</div>" : '');
		// append 4 direction arrows
		//  var flags = nodeData.relationship || '';
		// allow user to append dom modification after finishing node create of orgchart
		if (opts.createNode) {
			opts.createNode($nodeDiv, nodeData);
		}

		dtd.resolve($nodeDiv);
		return dtd.promise();
	}