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
numvariable, and they refer to it as of when theclickevent occurs. Since at that point it’s5(the last value it was ever assigned), you end up with all of them alerting5.If you want the event handler to refer to
numas 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:As you can see, we call
buildHandlerwhen hooking theclickevent and pass its return value intoclick.buildHandlercreates and returns a function that closes overval, the argument we pass to it. Sincevalis a copy of the number we want it to alert, and nothing ever changesval, 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:
It does the same thing (we define the function, then call it immediately), but without creating global
i,num,nums, andbtnvariables.Off-topic 2: You’ve used
for..inwith an array without doing any checks to make sure you’re only dealing with array indexes.for..indoes not loop through array indexes; it loops through object property names. Writingfor..inloops as though they looped through array indexes will bite you at some stage. Just use a normalforloop or do the necessary checks or use jQuery’seachfunction. More: Myths and realities offor..in