我已经这样做了:
<table id="tabla">
<tbody>
<tr><th>row1</th><td>w</td></tr>
<tr><th>row2</th><td>x</td></tr>
</tbody>
<tbody>
<tr><th>row1</th><td>y</td></tr>
<tr><th>row2</th><td>z</td></tr>
</tbody>
</table>
<script type="text/javascript">
function iterate() {
var table = document.getElementById("tabla").children;
for (b=0; b<table.length(); b++) {
var cells = table[b].children;
if(cells[0].innerHtml == "row1") {
if(cells[1].innerHtml == "w") {
table[b].style.display="none";
}
}
}
}
</script>
我的目的是找到表中满足条件的所有子项并停止显示它们。
我的代码无法运行,我不知道为什么。
有人知道吗?
最佳答案
- 您的 child
table
元素是tbody
- 没有
length()
函数,它是一个属性(只需使用length
) - 没有
innerHtml
,你应该使用innerHTML
cells[0]
您引用的实际上是行(而不是单元格),所以它是innerHTML ==<th>row1</th><td>w</td>
这是对您的代码的修复:
function iterate() {
var table = document.getElementById("tabla").children;
for (b=0; b<table.length; b++) {
var rows = table[b].children;
for (r=0; r<rows.length;r++) {
var cells = rows[r].children
if (cells[0].innerHTML == "row1") {
if (cells[1].innerHTML == "w") {
table[b].style.display="none";
}
}
}
}
}
iterate();
<table id="tabla">
<tbody>
<tr><th>row1</th><td>w</td></tr>
<tr><th>row2</th><td>x</td></tr>
</tbody>
<tbody>
<tr><th>row1</th><td>y</td></tr>
<tr><th>row2</th><td>z</td></tr>
</tbody>
</table>
关于javascript - HTML 查找并停止显示子表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40962221/