检查这段代码...
HTML
<span>TEST </span>
<div style="color:red">COlured div</div>
<div style="color:blue">COlured div</div>
<p style="color:red">Colourful TExt</p>
<p style="color:blue">Colourful TExt</p>
<p style="color:green">Colourful TExt</p>
<p style="color:brown">Colourful TExt</p>
<button onclick="changetobw()">CHANGE COLOR</button>
JavaScript
function changetobw() {
a = document.getElementsByTagName('p');
b = document.getElementsByTagName('div');
var i = 0;
do {
a[i].classList.add('nocolor');
b[i].classList.add('nocolor');
i++;
} while (i < a.length && i < b.length);
}
CSS
.nocolor {
color:#000 !important;
}
我在这里尝试做的是点击按钮使所有 div 和 span 字体颜色为“黑色”。
当计数器越过 i=2 时,我的代码(显然)中断了,因为只有 2 个 div,因此“i[2]”将是未定义的,因此循环中断。
有没有办法让循环在达到这一点后不中断?也许我没有完全理解我的观点。希望大家明白?
最佳答案
要像使用循环一样使用循环,您必须确保两个数组具有相同的长度。
显然,它们的长度不相等,因此要么将这个循环分成两个循环 (1),要么使用两个 if 语句来检查 i 与两个数组的长度 (2)。更好的做法是将 for
与 querySelectorAll
(3) 结合使用。
(1):
function changetobw() {
a = document.getElementsByTagName('p');
b = document.getElementsByTagName('div');
var i = 0;
do {
a[i].classList.add('nocolor');
i++;
} while (i < a.length);
i = 0;
do {
b[i].classList.add('nocolor');
i++;
} while (i < b.length);
}
(2) ( fiddle ):
function changetobw() {
a = document.getElementsByTagName('p');
b = document.getElementsByTagName('div');
var i = 0;
do {
if(i < a.length)
a[i].classList.add('nocolor');
if(i < b.length)
b[i].classList.add('nocolor');
i++;
} while (i < a.length || i < b.length);
}
(3)(fiddle):
function changetobw() {
var els = document.querySelectorAll('p, div');
for(var i = 0; i < els.length; i++) {
els.item(i).classList.add("nocolor");
}
}
关于javascript - 循环不应在遇到无效语句时中断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20096544/