如何通过父ID获取所有子属性并返回对象示例数组
我想要一个这样的结果:
pat_101 = adm_01-adm01, adm_01-adm02, adm_01-adm03
pat_102 = adm_04-adm04, adm_05-adm05, adm_06-adm06
pat_103 = adm_07-adm07, adm_08-adm08, adm_09-adm09
从这个html:
<div>
<ul>
<li id="pat_101">
<ul>
<li id ="adm_01" title="adm101"></li>
<li id ="adm_02" title="adm102"></li>
<li id ="adm_03" title="adm103"></li>
</ul>
</li>
<li id="pat_102">
<ul>
<li id ="adm_04" title="adm104"></li>
<li id ="adm_05" title="adm105"></li>
<li id ="adm_06" title="adm106"></li>
</ul>
</li>
<li id="pat_103">
<ul>
<li id ="adm_07" title="adm107"></li>
<li id ="adm_08" title="adm108"></li>
<li id ="adm_09" title="adm109"></li>
</ul>
</li>
</ul>
<div>
谢谢
答案 0 :(得分:0)
所以,这是一个答案,欢迎您访问stackoverflow.com:
var parents = document.getElementsByTagName("li")
var output = ""
var children
for (var ii=0, parent; parent=parents[ii]; ii++) {
children = parent.getElementsByTagName("li")
if (children.length) {
childArray = []
for (var jj=0, child; child=children[jj]; jj++) {
childArray[jj] = child.id
}
output += parent.id + " = " + childArray.join(", ") + "\n"
}
}
output = output.slice(0, -1)
console.log (output);
也许您希望逐行完成此工作,在Google上查找关键字并确保您了解这些关键字。准备就绪后,您可以关闭此窗口并自行重写方法,只需使用笔记,而无需查看原文。快乐的卡玛!