根据下面数组怎么生成三级联动菜单树
1个回答
展开全部
示例:
<div id="result"></div><script>
var result = document.getElementById('result') var arr = [
{"name": "广东","Id": -1,"parentId": null},
{"name": "湖北","Id": -2,"parentId": null},
{"name": "广州","Id": 44,"parentId": -1},
{"name": "武汉","Id": 58,"parentId": -2},
{"name": "深圳","Id": 12,"parentId":-1 },
{"name": "白云","Id": 741,"parentId": 44}
] var tree = {} var count = 0
array2Object(arr, tree, null) function array2Object (array, node, id) { var storage = [] var newArray = [] var newNode, newId for (var i = 0; i < array.length; i++) { if (array[i].parentId === id) {
node[array[i].name] = {}
storage.push(i)
count++
} else {
newArray.push(array[i])
}
} if (count !== arr.length) { for (var i = 0; i < storage.length; i++) {
array2Object(newArray, node[array[storage[i]].name], array[storage[i]].Id)
}
} else {
object2Html(result, tree)
}
} function object2Html (node, obj) { var storage = [] var tpl = node.innerHTML + '<ul>'
for (var key in obj) {
tpl = tpl + '<li data-name="' + key + '">' + key + '</li>'
if (!isEmptyObject(obj[key])) {
storage.push({ name: key, obj: obj[key]
})
}
}
tpl += '</ul>'
node.innerHTML = tpl if (storage.length !== 0) { for (var i = 0; i < storage.length; i++) {
object2Html(document.querySelector('li[data-name="' + storage[i].name + '"]'), storage[i].obj)
}
}
} function isEmptyObject (obj) { for (var key in obj) { return false
} return true
}</script>
<div id="result"></div><script>
var result = document.getElementById('result') var arr = [
{"name": "广东","Id": -1,"parentId": null},
{"name": "湖北","Id": -2,"parentId": null},
{"name": "广州","Id": 44,"parentId": -1},
{"name": "武汉","Id": 58,"parentId": -2},
{"name": "深圳","Id": 12,"parentId":-1 },
{"name": "白云","Id": 741,"parentId": 44}
] var tree = {} var count = 0
array2Object(arr, tree, null) function array2Object (array, node, id) { var storage = [] var newArray = [] var newNode, newId for (var i = 0; i < array.length; i++) { if (array[i].parentId === id) {
node[array[i].name] = {}
storage.push(i)
count++
} else {
newArray.push(array[i])
}
} if (count !== arr.length) { for (var i = 0; i < storage.length; i++) {
array2Object(newArray, node[array[storage[i]].name], array[storage[i]].Id)
}
} else {
object2Html(result, tree)
}
} function object2Html (node, obj) { var storage = [] var tpl = node.innerHTML + '<ul>'
for (var key in obj) {
tpl = tpl + '<li data-name="' + key + '">' + key + '</li>'
if (!isEmptyObject(obj[key])) {
storage.push({ name: key, obj: obj[key]
})
}
}
tpl += '</ul>'
node.innerHTML = tpl if (storage.length !== 0) { for (var i = 0; i < storage.length; i++) {
object2Html(document.querySelector('li[data-name="' + storage[i].name + '"]'), storage[i].obj)
}
}
} function isEmptyObject (obj) { for (var key in obj) { return false
} return true
}</script>
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询