利用深度优先遍历和递归
var acceptUnitNodes = null;//接收单位树形数据
function findParentNode(ids){ //ids 是子节点数组
var parentNodes = [];//所有父节点
var forfun = function (id,nodes) {
for(var i=0;i<nodes.length;i++){
var currentNode = nodes[i];
if(currentNode.id == id){
return currentNode.id;
}else if(currentNode.children){
var validNodeId = forfun(id,currentNode.children);
if(validNodeId&&parentNodes.indexOf(validNodeId)<0){
parentNodes.push(validNodeId)
}
if(validNodeId){
return currentNode.id;
}
}
}
}
$.each(ids,function (i,item) {
// selectedValues.push(item);
var validNodeId = forfun(item,acceptUnitNodes);
if(validNodeId&&parentNodes.indexOf(validNodeId)<0){
parentNodes.push(validNodeId);
}
})
console.info(parentNodes);
return parentNodes;
}