Question

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

Was it helpful?

Solution

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 ?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top