我对for
循环的机制有一个逻辑问题。
在下面的简单循环中,我预计前3个DIV元素的类将从box_1更改为box_2。然而,代替框1,2和3,蓝色框1,3和5变为蓝色。为什么循环似乎递增2而不是1?我确定我错过了什么。
for (let i = 0; i < 3; i++) {
document.querySelectorAll(".box_1")[i].className = "box_2";
}
&#13;
.box_1 {
padding: 8px;
margin: 0 0 16px 0;
font-size: 2rem;
color: white;
background-color: red;
}
.box_2 {
padding: 8px;
margin: 0 0 16px 0;
font-size: 2rem;
color: white;
background-color: blue;
}
&#13;
<div class="box_1">1</div>
<div class="box_1">2</div>
<div class="box_1">3</div>
<div class="box_1">4</div>
<div class="box_1">5</div>
<div class="box_1">6</div>
<div class="box_1">7</div>
<div class="box_1">8</div>
<div class="box_1">9</div>
<div class="box_1">10</div>
&#13;
答案 0 :(得分:4)
每次循环运行时,box_1
的第0个元素现在是 next 项,因为前一个第0个元素不再在该类中。换句话说,第二次循环是这个
<div class="box_2">1</div>
<div class="box_1">2</div> <-- This is now the [0] element
<div class="box_1">3</div> <-- This is now the [1] element
<div class="box_1">4</div>
<div class="box_1">5</div>
<div class="box_1">6</div>
<div class="box_1">7</div>
<div class="box_1">8</div>
<div class="box_1">9</div>
<div class="box_1">10</div>
答案 1 :(得分:4)
.box_1 {
padding: 8px;
margin: 0 0 16px 0;
font-size: 2rem;
color: white;
background-color: red;
}
.box_2 {
padding: 8px;
margin: 0 0 16px 0;
font-size: 2rem;
color: white;
background-color: blue;
}
&#13;
<div class="box_1">1</div>
<div class="box_1">2</div>
<div class="box_1">3</div>
<div class="box_1">4</div>
<div class="box_1">5</div>
<div class="box_1">6</div>
<div class="box_1">7</div>
<div class="box_1">8</div>
<div class="box_1">9</div>
<div class="box_1">10</div>
&#13;
NumberStyles.AllowCurrencySymbol
&#13;
关于NodeList与HTMLCollection https://hackernoon.com/htmlcollection-nodelist-and-array-of-objects-da42737181f9
的好文章