我有一个表格,当单击包含单元格的按钮时,要遍历每个单元格。但是,循环似乎不运行,我无法找到问题。为什么我的for循环不循环我的表格单元格? JavaScript
这里是代码片段:
element.onclick = function() {
//Sets color of selected element
for (var i = 0, cell; cell = document.getElementById('targetLocation').row.cells[i]; i++) {
if (cell.firstChild.style.background == "rgba(223, 22, 22, 0.53)") {
cell.firstChild.style.background = 'red';
}
else {
alert('Despite all, I loop')
};
};
};
<table id="targetLocation">
<tr>
<th></th>
<th>A</th>
<th>B</th>
<th>C</th>
<th>D</th>
<th>E</th>
<th>F</th>
<th>G</th>
<th>H</th>
<th>I</th>
<th>J</th>
</tr>
<tr>
<th>1</th>
<td><button class="cells" onmouseover="getTarget(this)">O</button></td>
<td><button class="cells" onmouseover="getTarget(this)">O</button></td>
<td><button class="cells" onmouseover="getTarget(this)">O</button></td>
<td><button class="cells" onmouseover="getTarget(this)">O</button></td>
<td><button class="cells" onmouseover="getTarget(this)">O</button></td>
<td><button class="cells" onmouseover="getTarget(this)">O</button></td>
<td><button class="cells" onmouseover="getTarget(this)">O</button></td>
<td><button class="cells" onmouseover="getTarget(this)">O</button></td>
<td><button class="cells" onmouseover="getTarget(this)">O</button></td>
<td><button class="cells" onmouseover="getTarget(this)">O</button></td>
</tr>
</table>
下面是相应的JavaScript:
对于澄清: “元素” 是你在上空盘旋的元素。当鼠标悬停在单元格上时,背景颜色将变为rgba(223,22,22,0.53)。如果您目前在该单元格上方悬停,并且您单击该按钮,则应该变成红色。 onclick函数本身就可以工作,如果我在该函数中设置了一个警报,例如,它可以工作,所以我猜测它是for循环被破坏了。
你可以发布一个工作片断? – Nisarg
行应该是什么?只有['rows'](https://developer.mozilla.org/en-US/docs/Web/API/HTMLTableElement/rows)。 – PeterMader
@PeterMader感谢您的提示! –