Javascript array problem: Cannot read property 'src' of undefined
This script has been running over at waterbirds.org for years. Now it's broken for开发者_C百科 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);
}
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 to preLoad[j]
j
equals 96
, and preload[96]
is really undefined.
Wrap your banner in anonymous self-executing function, for example, to make vars local, and you're done:
(function(){
var slideShowSpeed;
var j = 0;
var p;
var preLoad = new Array();
// to keep rotate_banner global, save it as a property of window object
window.rotate_banner = function() {
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);
}
})()
And remember: global variables are evil! =)
精彩评论