0
for (key in this.mybutton)
       button = this.mybutton[key]

       $(button).click(function() {
            console.log("click:" + button)
       });

The result is always the name of the last button. How can I add multiple listeners in jQuery/javascript or erase the javascript reference button to a string in the for.

thanks in advance

1
  • Using 'this' or maybe you need a cosure there. Could you provide a working sample as jsfiddle which show what are you looking for? Commented Jul 23, 2013 at 10:20

1 Answer 1

2

You need a closure new scope :

for (key in this.mybutton)
   (function(button) {
       $(button).click(function() {
            console.log("click:" + button)
       });
   })(this.mybutton[key]);
}

or just use this:

$(button).click(function() {
    console.log("click:" + this)
});

Concatenating a DOM element and a string in the console log doesn't seem like a very good idea ?

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

3 Comments

No, not a closure (the event handler is already a closure). You need to create a new scope. See my comments here for a more extensive explanation (this is just regarding the first snippet, of course the second one is a much better solution anyway).
@FelixKling - thanks, that's a good explanation, and even if I understood why it worked, I've never really thought about the fact that any function will create a closure, and as such the closure isn't the reason it works, passing the parameter to keep it constant within the new scope is!
thanks,exactly what i want. The concatenation was just to give an simple example of my problem, it's doesn't have a real utility :p

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.