I’m using jQuery and I have a strange thing that I don’t understand. I have some code:
for (i = 1; i <= some_number; i++) {
$("#some_button" + i).click(function() {
alert(i);
});
}
“#some_button” as the name says – they are some buttons. When clicked they should pop-up a box with it’s number, correct? But they don’t. If there is 4 buttons, they always pop-up “5” (buttons count + 1). Why is that so?
It has to do with JavaScript scoping. You can get around it easily by introducing another scope by adding a function and having that function call itself and pass in i:
This creates a closure – when the inner function has access to a scope that no longer exists when the function is called. See this article on the MDC for more information.
EDIT: RE: Self-calling functions: A self-calling function is a function that calls itself anonymously. You don’t instantiate it nor do you assign it to a variable. It takes the following form (note the opening parens):
Relating this to the question, the body of the anonymous function would be:
Combining these together, we get the answer in the first code block. The anonymous self-calling function is expecting an argument called
j. It looks for any element with an id ofsome_buttonwith the integer value ofjat the end (e.g. some_button1, some_button10). Any time one of these elements is clicked, it alerts the value ofj. The second-to-last line of the solution passes in the valuei, which is the loop counter where the anonymous self-calling function is called. Done another way, it might look like this: