检查这个小提琴:JSFiddle
HTML:
<table class="myTable">
<tr>
<th>Some text</th>
<td class="align">
<span class=" someStyle">1</span>/<span class="otherStyle">15</span>
</td>
<th>Some text</th>
<td class="align">
<span class=" someStyle">2</span>/<span class="otherStyle">16</span>
</td>
</tr>
<tr>
<th>Some text</th>
<td class="align">
<span class="">3</span>/<span class="">17</span>
</td>
<th>Some text</th>
<td class="align">
<span class="otherStyle">4</span>/<span class=" someStyle">18</span>
</td>
</tr>
<tr>
<th>Some text</th>
<td class="align">
<span class="otherStyle">5</span>/<span class=" someStyle">19</span>
</td>
<th>Some text</th>
<td class="align">
<span class="">6</span>/<span class="">20</span>
</td>
</tr>
<tr>
<th>Some text</th>
<td class="align">
<span class="">7</span>/<span class="">21</span>
</td>
<th>Some text</th>
<td class="align">
<span class=" someStyle">8</span>/<span class="otherStyle">22</span>
</td>
</tr>
<tr>
<th>Some text</th>
<td class="align">
<span class="">9</span>/<span class="">23</span>
</td>
<th>Some text</th>
<td class="align">
<span class="otherStyle">10</span>/<span class=" someStyle">24</span>
</td>
</tr>
<tr>
<th>Some text</th>
<td class="align">
<span class="otherStyle">11</span>/<span class=" someStyle">25</span>
</td>
<th>Some text</th>
<td class="align">
<span class="otherStyle">12</span>/<span class=" someStyle">26</span>
</td>
</tr>
<tr>
<th>Some text</th>
<td class="align">
<span class=" someStyle">13</span>/<span class="otherStyle">27</span>
</td>
<th>Some text</th>
<td class="align">
<span class=" someStyle">14</span>/<span class="otherStyle">28</span>
</td>
</tr>
</table>
JavaScript:
var myTbl = document.getElementsByClassName("myTable")[0];
var tSomeStyleClasses = myTbl.getElementsByClassName("someStyle");
console.log(tSomeStyleClasses);
for (i=0;i<tSomeStyleClasses.length;i++) {
console.log(tSomeStyleClasses[i].classList);
//tSomeStyleClasses[i].classList.remove("someStyle");
}
var tOtherStyleClasses = myTbl.getElementsByClassName("otherStyle");
console.log(tOtherStyleClasses);
for (i=0;i<tOtherStyleClasses.length;i++) {
console.log(tOtherStyleClasses[i].classList);
//tOtherStyleClasses[i].classList.remove("otherStyle");
}
并检查控制台日志。 someStyle 和 otherStyle 各有 10 个条目。现在取消注释//tSomeStyleClasses[i].classList.remove("someStyle");
and //tOtherStyleClasses[i].classList.remove("otherStyle");
并运行小提琴。再次检查控制台日志。应删除 2 x 10 个样式,但它只删除 5 个样式。
我想知道为什么?
返回值来自.getElementsByClassName()
is a live节点列表。它的“实时”意味着当您更改列表中的元素时,列表本身会自动更新。因此,当你remove用于查找元素的类,列表会变得更短。因为您使用数字索引进行迭代,所以最终会跳过元素。
解决这个问题的一个好方法是使用一个简单的while
循环并仅对列表的第一个元素进行操作,直到列表为空:
var tSomeStyleClasses = myTbl.getElementsByClassName("someStyle");
while (tSomeStyleClasses.length) {
tSomeStyleClasses[0].classList.remove("someStyle");
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)