-2

我正在尝试制作间隔功能,它将每 10 秒更改一次选定的 div。当我在第一页时,我希望它显示第一个数组中的项目,当我在第二页时,我想要数组 2,等等。这是我到目前为止得到的:

var timedFunc = '';
var index= new Array(20)
index[0]="index1";
index[1]="index2.";
..

var indextwo= new Array(20)
indextwo[0]="index1";
indextwo[1]="index2";

var tmp = 0;
function display_index(nameofarray) {
if (tmp < 0) { tmp = nameofarray.length-1; }
if (tmp > nameofarray.length-1) { return false; }
document.getElementById('robot').innerHTML = nameofarray[tmp];
tmp = tmp + 1;
}
function indexInterval(m) {
  switch(m) {
    case 1: timeFunc = setInterval("display_index(index)",1000);
    case 2: timeFunc = setInterval("display_index(indextwo)",1000);
    case 3: timeFunc = setInterval("display_index(indexthree)",1000);
    case 4: timeFunc = setInterval("display_index(indexfour)",1000);
  }
}
4

1 回答 1

1

要在间隔计时器上循环遍历数组,可以将所需的数组传递给函数,然后使用该函数在间隔计时器上循环遍历数组,如下所示:

var index0 = ["text1", "text2", "text3"];
var index1 = ["text1", "text2", "text3"];

function startMyInterval(array) {
    var index = 0;
    var item = document.getElementById('robot');
    setInterval(function() {
        // if we reached the end of the array, start back at beginning
        if (index >= array.length) {
            index = 0;
        }
        item.innerHTML = array[index]; 
        ++index;
    }, 10000);
}

// figure out which array of text values you want to use
// for this particular page index0 or index1
// and pass that array to startMyInterval()
startMyInterval(x);

这种类型的实现避免了该switch语句并避免将文本传递给setInterval(). 它还使用函数闭包来跟踪setInterval()回调所需的状态。

于 2012-06-09T18:34:46.937 回答