The following page displays five buttons, clicking each button gets alert '5'. I want when I click the first button, I get alert '1', the second button '2' ...etc.
<!doctype html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
</head>
<body>
<div id="nums"></div>
<script type="text/javascript">
var nums = [1,2,3,4,5];
for(var i in nums){
var num = nums[i];
var btn=$('<button></button>').text(num).click(function(){alert(num);});
$('#nums').append(btn);
}
</script>
</body>
</html>
The event handler functions you're creating in the loop have an enduring reference to the variables in scope where they're created, not a copy of those variables as of when the function was created. This is how closures work (more: Closures are not complicated). So all of your handler functions refer to the same num
variable, and they refer to it as of when the click
event occurs. Since at that point it's 5
(the last value it was ever assigned), you end up with all of them alerting 5
.
If you want the event handler to refer to num
as of when the handler was created, you have to have the handler close over something that won't change. The usual way is to have a function that builds your handler function, and have the handler function close over an argument to that builder function:
var nums = [1,2,3,4,5];
for(var i in nums){
var num = nums[i];
var btn=$('<button></button>').text(num).click(buildHandler(num));
$('#nums').append(btn);
}
function buildHandler(val) {
return function(){alert(val);};
}
As you can see, we call buildHandler
when hooking the click
event and pass its return value into click
. buildHandler
creates and returns a function that closes over val
, the argument we pass to it. Since val
is a copy of the number we want it to alert, and nothing ever changes val
, the functions perform as desired.
Off-topic 1: You're creating a lot of global variables in that code. The global namespace is already very crowded, I recommend avoiding creating more globals whenever you can avoid it. I'd wrap that code in a function so that the varibles are all local to that function:
<script>
(function() {
var nums = [1,2,3,4,5];
for(var i in nums){
var num = nums[i];
var btn=$('<button></button>').text(num).click(buildHandler(num));
$('#nums').append(btn);
}
function buildHandler(val) {
return function(){alert(val);};
}
})();
</script>
It does the same thing (we define the function, then call it immediately), but without creating global i
, num
, nums
, and btn
variables.
Off-topic 2: You've used for..in
with an array without doing any checks to make sure you're only dealing with array indexes. for..in
does not loop through array indexes; it loops through object property names. Writing for..in
loops as though they looped through array indexes will bite you at some stage. Just use a normal for
loop or do the necessary checks or use jQuery's each
function. More: Myths and realities of for..in