开发者

Issue with scope and/or click listener in Javascript/jquery

I'm trying to work out a trivial issue:

var setListeners = function()
        {
            for(var i in sliders)
            {
                sliders[i开发者_如何学编程].switchBtn.click(function()
                {
                    alert(i);
                });
            }
        }

There are three elements in sliders, so 3 switchBtn's are given a click listener. I expected that clicking the first button would alert with a '0', the second a '1' and the third a '2'. However when I press each button, I just get '2'.

Could someone please point out why the value of i is overridden for each new listener function?


Use a closure so the internal i isn't always bound to outer scope (which will be the last value at the end of the loop).

Here the value of i is being set to j.

var setListeners = function()
    {
        for(var i in sliders)
        {
            sliders[i].switchBtn.click((function(j)
            {
                return function() { alert(j) };
            })(i);
        }
    }

jsFiddle.


since i is outside of the function, you're always referencing the same variable and it's always 2. You need a closure to get this to work properly:

sliders[i].switchBtn.click((function(n){
   return function(){
      alert(n);
   }
})(i));

n (was i) is now bound in a closure and your alerts will show properly.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜