I am writing a jQuery plugin that introduces a new method foo()that creates some element <img>inside the DOM object on which it is called. I store pointers to these images in an array images. At the end of the method, I call setInterval("someFunction(images)", 1000), which should periodically perform some actions (for example, change src) on the images.
Here is a very short version of my code:
(function($) {
$.fn.foo = function () {
return this.each (function () {
$box = $("#"+this.id);
images = new Array();
for (i = 0; i<4; i++) {
images[i] = $("<img>");
$box.prepend(images[i]);
}
setInterval("someFunction(images)", 1000);
});
}
function someFunction(images) {
for (i = 0; i<images.length; i++) {
images[i].attr("src", "foo"+(parseInt(Math.random()*5)));
}
}
})(jQuery);
Everything works if I apply foo()to one element, but if I apply it to several elements, all the latest updates apply to the last element. I assume this is because the array is passed as a reference to someFunction, and then overwritten.
slice() , , , . , , - .
, , , , .