0

当我开始显示这就是我得到的:Uncaught TypeError: Cannot read property 'src' of undefined指向function:(runPicGal见下文)。希望你能帮忙。注意:奇怪的是我看到图片改变了一次然后我得到了错误。

完整的 JS 文件:

var picForDiashow;
var diashowPicArray = [];
var diashowPicArrayIndex = 0;

diashowPicArray [0] = new Image(); diashowPicArray [0].src = "./pics/1.jpg";
diashowPicArray [1] = new Image(); diashowPicArray [0].src = "./pics/2.jpg";
diashowPicArray [2] = new Image(); diashowPicArray [0].src = "./pics/3.jpg";
diashowPicArray [3] = new Image(); diashowPicArray [0].src = "./pics/4.jpg";
diashowPicArray [4] = new Image(); diashowPicArray [0].src = "./pics/5.jpg";



function initForDiashow () {

    picForDiashow = document.getElementById("diashowPic");
}

window.onload = initForDiashow;





function startDiashow () {

    picInterval = window.setInterval(runPicGal, 1000);
}





function stopDiashow () {

    window.clearInterval(picInterval);
}




function runPicGal () {

    diashowPicArrayIndex++;

    if (diashowPicArrayIndex > diashowPicArray.length) {
        diashowPicArrayIndex = 0;
    } 
    picForDiashow.src = diashowPicArray[diashowPicArrayIndex].src;

}
4

1 回答 1

1

您总是将元素添加到数组的第一个位置。因此,只有第一个元素diashowPicArray[0], 将是可访问的。将初始化更改为以下内容:

diashowPicArray [0] = new Image(); diashowPicArray [0].src = "./pics/1.jpg";
diashowPicArray [1] = new Image(); diashowPicArray [1].src = "./pics/2.jpg";
diashowPicArray [2] = new Image(); diashowPicArray [2].src = "./pics/3.jpg";
diashowPicArray [3] = new Image(); diashowPicArray [3].src = "./pics/4.jpg";
diashowPicArray [4] = new Image(); diashowPicArray [4].src = "./pics/5.jpg";

此外,在您的比较中,您不应该使用diashowPicArrayIndex > diashowPicArray.length. 否则,您将尝试访问diashowPicArray[5],这是超出范围的。改用==

diashowPicArrayIndex++;
if (diashowPicArrayIndex == diashowPicArray.length) {
    diashowPicArrayIndex = 0;
} 

或者,使用模运算简化上述行:

diashowPicArrayIndex = (diashowPicArrayIndex + 1) % diashowPicArray.length;
于 2012-09-02T12:51:07.630 回答