我试图隐藏特定唯一 ID 下的某些行。示例:
<tbody id="row0">
<tr class="state0"></tr>
<tr class="state1"></tr>
<tr class="state2"></tr>
<tr class="state3"></tr>
</tbody>
我可以通过以下方式找到特定行:
var state0 = document.getElementById('row0').getElementsByClassName('state0');
var state1 = document.getElementById('row0').getElementsByClassName('state1');
然后隐藏两行,如下所示:
for (let index in state0) {state0[index].style.display = 'none'}
for (let index in state1) {state1[index].style.display = 'none'}
并最终得到一个错误,指出一旦我隐藏了 state0 的行,state1 就不再定义了。每当我隐藏一行时,就会发生这种情况,即使我再次通过 id 获取元素后,下一行最终也未定义。有人可以帮助我并解释为什么会发生这种情况吗?
最佳答案
<tbody id="row0">
<tr class="state0"></tr>
<tr class="state1"></tr>
<tr class="state2"></tr>
<tr class="state3"></tr>
</tbody>
var state0 = document.querySelector('#row0 > .state0');
var state1 = document.querySelector('#row0 > .state1');
state0.style.dysplay = 'none';
state1.style.dysplay = 'none';
此外,
for (index in state0) {
// index will be a property of the state0 object
// state0 is not an array and has other properties than child indices, for example length, item, namedItem ...
// state0['length'] have not property 'style'
}
你可以使用
for (var i = 0; i <state0.length; i ++) {
var indexOfChild = state0 [i];
...
}
关于javascript - 为什么在更改另一个变量的显示后我的变量变得未定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55952921/