使用 Sizzle 库作为依赖项,以下将迭代所有<div class="item">
父级,然后迭代每个父级的所有子级。
<script type='text/javascript' src='https://raw.github.com/jquery/sizzle/master/sizzle.js'></script>
<script type='text/javascript'>
var itemDivs = Sizzle('.item')
var items = []
for (var i = 0; i < itemDivs.length; i++) {
var children = Sizzle('div', itemDivs[i])
var item = {}
for (var j = 0; j < children.length; j++) {
item[children[j].id] = children[j].innerText || children[j].textContent
}
items.push(item)
}
console.log(items)
</script>
如果您HTML
有其他元素,则需要修改上述代码以仅查找数组所需的特定子项。测试的 HTML 是:
<div class="item">
<div id="itemid">001</div>
<div id="itemname">name 1</div>
</div>
<div class="item">
<div id="itemid">002</div>
<div id="itemname">name 2</div>
</div>
我在 Chrome DevTools 控制台中得到的输出是
[Object, Object]
0: Object
itemid: "001"
itemname: "name 1"
__proto__: Object
1: Object
itemid: "002"
itemname: "name 2"
__proto__: Object
length: 2
__proto__: Array[0]