javascript - 循环不应在遇到无效语句时中断

标签 javascript html

检查这段代码...

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

DEMO

我在这里尝试做的是点击按钮使所有 div 和 span 字体颜色为“黑色”。

当计数器越过 i=2 时,我的代码(显然)中断了,因为只有 2 个 div,因此“i[2]”将是未定义的,因此循环中断。

有没有办法让循环在达到这一点后不中断?也许我没有完全理解我的观点。希望大家明白?

最佳答案

要像使用循环一样使用循环,您必须确保两个数组具有相同的长度。

显然,它们的长度不相等,因此要么将这个循环分成两个循环 (1),要么使用两个 if 语句来检查 i 与两个数组的长度 (2)。更好的做法是将 forquerySelectorAll (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/

相关文章:

javascript - 向数组添加新元素

jquery - 如何使用JQuery设置不同的CSS属性?

css - 将 6 个以上的 div 与每行 3 个 div 对齐

html - CSS:如何放大一个div的子div并在调整屏幕大小时将两个图像设置为顶部和底部固定

html - 将使用哪个样式表? (IE条件语句)

javascript - 在 javascript 中为未选中的复选框设置值 null

javascript - 修复 Mailchimp 选择加入功能 - 从测试到生产

javascript - iframe 中的元素如何捕获关键事件?

javascript - 更改字母算法,在 JSBIN 中有效,但在 Coderbyte 中无效,寻求澄清

javascript - 触摸事件在 IOS 7 Iphone 中不起作用