我有一个像html这样的网格
<div class="grid-container" id="grid-container">
<div class="grid-row">
<div class="grid-cell red"><p class="label">R</p></div>
<div class="grid-cell"></div>
<div class="grid-cell blue"><p class="label">B</p></div>
</div>
<div class="grid-row">
<div class="grid-cell"></div>
<div class="grid-cell white"><p class="label">W</p></div>
<div class="grid-cell"></div>
</div>
<div class="grid-row">
<div class="grid-cell"></div>
<div class="grid-cell blue"><p class="label">B</p></div>
<div class="grid-cell blue"><p class="label">B</p></div>
</div>
</div>
我希望能够单独为每个单元格进行JavaScript更新。为此我尝试编写一个脚本来获取网格的所有子节点,然后再次获取每行的子节点。但是,当我测试输出时,三行返回正常,但是它们的子节点返回7个对象而不是3.我很困惑......
function myFunction() {
var c = document.getElementById("grid-container").childNodes;
var b;
var txt = "";
for (var i = 0; i < c.length; i++) {
txt = txt + "Row: " + c[i].nodeName + "<br>";
b = c[i].childNodes;
for (var j = 0; j < b.length; j++) {
txt = txt + "Cell: " + b[i].nodeName + " Value: " + b[i].className + "<br>";
}
}
document.getElementById("demo").innerHTML = txt;}
以下是它给我的输出:
答案 0 :(得分:0)
为了向Loilo撰写答卷,只需使用children
而不是childNodes