문제

누구든지 다음 코드가 여기에 정의 된 색상 배열을 순환하지 못하는 이유를 말해 줄 수 있습니까?

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

}

모든 도움은 대단히 감사합니다. 감사

도움이 되었습니까?

해결책

몇 가지 다른 것들. 첫째, 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

편집하다 또한 간격 핸들러에서 추가 괄호를 고정하십시오.

다른 팁

구문 오류, 여분의 오른쪽 괄호 ')' 줄 끝에서 :

currElm.style.background = colors[(nextColor++)%(colors.length)]);

나는 여분의 오른쪽 괄호도 본다!

그러나 NextColor 변수는 Colors Array 바로 다음에 이미 0으로 초기화되었습니다.

이것은 Firebug의 직업입니다. SetInterval 호출에 도달하기 직전에 중단 점을 설정하고 SetInterval의 익명 함수에있는 다양한 변수를 테스트 할 수 있습니다.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top