I have an options object like this:
//buttons = html-button elements with id's
buttonTypes: {
"open" : ['#button1', '#button2'],
"close" : ['#button3', '#button4']
}
Now I want to assign click handlers to the elements in each buttonTypes.key.
The buttons which are related to "open" shall call a function with the same name
and those related to "close" shall call a function called close
so I wrote this loop:
for(a in buttonTypes) {
$(buttonTypes[a]).each(function(i,button){
$(button).click(function(e) {
that[a]();
});
});
}
The problem:
When I click on the buttons, the only function called is close() – so it seems it is always the last one. What do I do wrong?
Because
that[a]();isn’t evaluated until you click the button; and by that point, it’sclose.What you should do instead is create a local copy of
a;Also don’t forget to
vara (for (var a in buttonTypes)).