为什么更改另一个变量的显示后我的变量变得不确定?

时间:2019-05-02 12:52:15

标签: javascript loops undefined getelementbyid getelementsbyclassname

我正在尝试隐藏特定唯一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获得element时,下一行也仍然是不确定的。有人可以帮我解释一下为什么会发生这种情况吗?

1 个答案:

答案 0 :(得分:1)

INSERT INTO foo (id) VALUES (NULL) ;

1 row(s) affected

SELECT * FROM quicknotedesc ;

custid  moonid  
------  ------
     1       1
     1       2

此外,

<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'
}