2

我有一些链接,想自动一个一个地传递焦点。我正在使用下面的代码。通过焦点效果很好,但只有一次。第一次焦点传递,链接改变颜色,然后传递到下一个。前一个再次变黑,下一个被涂成红色。没问题。但是当它到达最终链接时不会重新启动。

var i = 0;
var letras = document.getElementsByTagName("a");

function pasaLink() {
    if (i == 0) {
        letras[letras.length-1].style.color = "black";
    } else {
        letras[i-1].style.color = "black";
    }
    letras[i].style.color = "red";
    letras[i].focus();
    i++;
    if (i > letras.length) {
        i= 0;
    }
    setTimeout("pasaLink()",2000);
}

最后ifi=0;我试图在到达最终元素时返回初始索引,然后重新启动以迭代letras. 这个函数在 body.onload() 中调用。

任何想法为什么它不起作用?

4

2 回答 2

2

Change your if to:

if (i >= letras.length) {   
   i= 0;     
} 

Working example:
http://jsfiddle.net/nivas/Nn62Q/
(click the Orig Button to see the behavior of your code and the New button to see the behavior of the new one. I have added a try...catch to show the error)

Explanation:
Let us say there are five a tags. You make i = 0 when i > 6 (i.e., 6). But when i becomes 5, letras[i].style.color = "red"; at the beginning of the function fails and an exception is throws a exception. The flow stops here so the if (i > letras.length) will never be reached.

于 2012-05-18T19:00:48.110 回答
0

你的情况不应该是

if (i == letras.length) {
    i= 0;
}

反而?

一旦i等于数组的长度,请重置。

于 2012-05-18T18:57:19.500 回答