For easier explanation, please see the corresponding jsFiddle
This is the code I'm calling in a loop:
var eventNames = ["click", "dblclick", "contextmenu"];
for (var i = 0; i < eventNames.length; ++i) {
var crtName = eventNames[i];
$("#" + crtName).click(function () {
alert("Event " + crtName);
});
}
Sure, when the handler is called, crtName
is always "contextmenu"
because at this point, the for
-loop has ended and i
is always pointing to the highest possible value.
Note: In the current example, I'm using the click
function from jQuery. In my real application, there's another framework being called to register an event handler. So this is just an example and it cannot be changed. Neither can I add parameters being passed to the handler when the event occurs. Therefore it's not a jQuery question.
As well, it's similar to the question "need help understanding JS code", except for the important fact that I'm not calling my event handler myself!
Basically: I would like the variable crtName
to be populated when the handler is being registered, not when it's called.