0

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?

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

11 Comments

wow, you seriously just edited your post that you made first (and incorrectly) to copy mine character-for-character? wow...
@cwolves No, actually, I was testing it on jsFiddle, the similarity is a coincidence I promise you. I've answered this type of question a few times before, so don't assume because I used similar code I stole it.
k, sorry. timing was just bad since you edited it right after I posted :)
@cwolves I noticed you gave the correct answer first. My first answer I forgot the pattern and I quickly remembered about the self invoking function so I went to fiddle to work it out (I try to test all my non trivial JavaScript code before I post it).
@downvoter Thanks :) @cwolves Proof that I at least knew to answer it (sometimes my memory isn't as good as it should be) :)
|
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.