JavaScript 数组问题:无法读取属性“src”未定义的
该脚本已在 waterbirds.org 上运行多年。现在由于某种原因它坏了。它抛出“无法读取未定义的属性'src'”错误,我已将其跟踪到 preLoad[j].src (runSlideShow 函数的第一行)作为问题,因为我可以在那里放置图像链接地址并且它可以工作。知道是什么原因造成的吗?
// Waterbird Society Theme for Wordpress
// Rotating image banner applet
//
// Usage:
//<body onLoad='rotate_banner(slideShowSpeed, "Image1.jpg", "Image2.jpg"...)'>
var slideShowSpeed;
var j = 0;
var p;
var preLoad = new Array();
function rotate_banner() {
var args = rotate_banner.arguments;
slideShowSpeed = Number(args[0]);
p = args.length;
for (i = 0; i < p-1; i++) {
preLoad[i] = new Image();
preLoad[i].src = args[i+1];
}
runSlideShow();
}
function runSlideShow() {
document.images['SlideShow'].src = preLoad[j].src;
j++;
if (j > (preLoad.length - 1)) j = 0;
t = setTimeout('runSlideShow()', slideShowSpeed*1000);
}
This script has been running over at waterbirds.org for years. Now it's broken for some reason. It throws a "Cannot read property 'src' of undefined" error and I've tracked it down to preLoad[j].src (first line of runSlideShow function) as the problem because I can put a image link address there and it works. Any idea what's causing the problem?
// Waterbird Society Theme for Wordpress
// Rotating image banner applet
//
// Usage:
//<body onLoad='rotate_banner(slideShowSpeed, "Image1.jpg", "Image2.jpg"...)'>
var slideShowSpeed;
var j = 0;
var p;
var preLoad = new Array();
function rotate_banner() {
var args = rotate_banner.arguments;
slideShowSpeed = Number(args[0]);
p = args.length;
for (i = 0; i < p-1; i++) {
preLoad[i] = new Image();
preLoad[i].src = args[i+1];
}
runSlideShow();
}
function runSlideShow() {
document.images['SlideShow'].src = preLoad[j].src;
j++;
if (j > (preLoad.length - 1)) j = 0;
t = setTimeout('runSlideShow()', slideShowSpeed*1000);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的代码一切正常,除了它是全局运行的,因此所有
var
声明都会创建全局变量。waterbirds.org 上的确切问题是
j
变量在preLoad[j]
之前和之前的某处定义j
等于 < code>96,而preload[96]
实际上是未定义的。例如,将您的横幅包装在匿名自执行函数中,以使变量本地化,然后您就完成了:
并记住:全局变量是邪恶的! =)
Everything is alright with your code except for it is run globally so all
var
declarations create global variables.The exact issue on waterbirds.org is that
j
variable is defined somewhere before and by the moment it comes topreLoad[j]
j
equals96
, andpreload[96]
is really undefined.Wrap your banner in anonymous self-executing function, for example, to make vars local, and you're done:
And remember: global variables are evil! =)