I am building a function to update a HTML node's background position at a regular basis. The function works for a single node, but when called upon multiple node (in the 开发者_运维问答following example), only the last node is affected by this function.
According to the alert(index) within the function, setInverval() is called for each node.
I cannot figure out why it doesn't take effect.
http://jsfiddle.net/GqNgs/1/
var bgImgAnimate = function (settings) {
$.each(settings.nodeList, function (index, node) {
thisNode = $(node);
var thisPosition;
setInterval(function () {
alert(index);
//calculate the position before position the image
thisPosition = - settings.frameWidth * settings.currentFrame;
thisNode.css('backgroundPosition', (thisPosition + 'px') + ' ' + (settings.verticalPos + 'px'));
}, settings.interval);
});
};
var settings = {
nodeList: $('#star1, #star2, #star3'),
verticalPos: 0,
currentFrame: 1,
frameWidth: 26,
startTime: 2,
frameNumber: 10,
interval: 200
}
bgImgAnimate(settings);
Your variable thisNode
is global, so once you execute your function you quickly loop through all three elements (what you call nodes), but when that's done, all three functions that will execute at the interval will refer to a single element (and therefore only that one will be changed, the fact that your alerts showed you the correct answer, is because each alert references a differently and correctly scoped index
value).
Simple fix, change:
thisNode = $(node);
to:
var thisNode = $(node);
http://jsfiddle.net/GqNgs/2/
As an aside, it would probably be more scalable to set only one interval function, and each time it's called move the background (or do whatever manipulation you want) on all elements, rather than an interval for each element.
It is because of you iterate nodeList and you ASSIGN thisNode each time and then you pass it to the interval. But what happens is that thisNode is three times rewrited (after the loop it reffers to the LAST node) and AFTER that three intervals are executed all with the same thisNode variable which at the moment is the LAST node.
精彩评论