0

谁能告诉我为什么以下代码可能不会循环遍历此处定义的颜色数组:

var colors = ["white", "yellow", "orange", "red"];

这是有问题的代码行:

setInterval(function(){
          currElm.style.background = colors[(nextColor++)%(colors.length)]);
      }, 500);

看起来这应该可行,我已经看到了几个例子,其中的代码就像这样产生了颜色循环效果。有人看到上面(或下面)代码有问题吗?

整个功能(正在进行中):

function setHighlight(elmId, index, songLength){
//alert("called set highlight, params are " + elmId + " " + index + " " + songLength);
var colors = ["white", "yellow", "orange", "red"];
var nextColor = 0;
if(index < 10)
    index = "000" + (index);
  else if (index < 100)
    index = "000" + (index);
  else if(index < 1000)
    index = "0" + (index);
  if(index >= 1000)
    index = index;
//alert("called set highlight, params are " + elmId + " " + index + " " + songLength);

//this will be useful for finding the element but pulsate will not work, need to       research animations in javascript

var mainElm = document.getElementById('active_playlist');
var elmIndex = "";

for(var currElm = mainElm.firstChild; currElm !== null; currElm = currElm.nextSibling){
  if(currElm.nodeType === 1){

  var elementId = currElm.getAttribute("id");

  if(elementId.match(/\b\d{4}/)){

    elmIndex = elementId.substr(0,4);
    alert(currElm.getAttribute('id'));

    if(elmIndex == index){
        setInterval(function(){
          currElm.style.background = colors[(nextColor++)%(colors.length)]);
      }, 500);
    }
  }
}
}//end for

}

非常感谢所有帮助。谢谢

4

3 回答 3

1

语法错误,行尾有多余的右括号')'

currElm.style.background = colors[(nextColor++)%(colors.length)]);
于 2009-06-24T02:28:39.840 回答
1

几个不同的东西。首先,看起来您正在匹配 id 包含空格后跟 4 位数字的元素。我认为 id 中不允许有空格。我真的很想看到应该匹配的元素的 HTML。其次,我认为您想将 currElm 分配给将在您的 setInterval 处理程序中捕获的新变量。如果你不这样做,我认为它可能总是指最后一个匹配的元素,而不是每个匹配的元素。

for(var currElm = mainElm.firstChild; currElm !== null; currElm = currElm.nextSibling){

  if(currElm.nodeType === 1){

    var elementId = currElm.getAttribute("id");

    if(elementId.match(/\b\d{4}/)){

      elmIndex = elementId.substr(0,4);
      alert(currElm.getAttribute('id'));

      if(elmIndex == index){
          var that = currElm;
          setInterval(function(){
              that.style.background = colors[(nextColor++)%(colors.length)];
          }, 500);
      }
    }
  }

}//end for

编辑还修复了间隔处理程序中的额外括号。

于 2009-06-24T02:29:38.857 回答
0

我也看到了额外的右括号!

但是 nextColor 变量已经初始化为零,就在颜色数组之后。

这是 Firebug 的工作。您可以在调用 setInterval 之前设置断点,并测试 setInterval 的匿名函数中的各种变量。

于 2009-06-24T02:32:19.507 回答