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=".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 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./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>
Share
Improve this question
edited Nov 29, 2021 at 21:38
Brian Tompsett - 汤莱恩
5,89372 gold badges61 silver badges133 bronze badges
asked Jul 26, 2011 at 3:19
Peter LongPeter Long
4,0322 gold badges24 silver badges18 bronze badges
1
- Thank you all for the excellent answers! I clicked '+1' for all of the correct answers. But I can only accept one answer. Really sorry for that. – Peter Long Commented Jul 26, 2011 at 4:58
6 Answers
Reset to default 5JavaScript only has function scope, so in your example there is only one num
, which keeps being modified, and by the time the click event is invoked, it equals five. To get around this, you have to create the right closure with a new function scope, like this:
var nums = [1,2,3,4,5];
var createClick = function (num) { return function() { alert(num); }; };
for(var i in nums){
var num = nums[i];
var btn=$('<button></button>').text(num).click(createClick(num));
$('#nums').append(btn);
}
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 plicated). 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 remend 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
Change this line:
var btn=$('<button></button>').text(num).click(function(){alert($(this).text()});
All of the click
handlers you create refer back to the same global variable num
, which will be 5 after the loop has run and still five at the point when you actually do click to trigger the handler and display the alert.
Two ways to get around that are as follows:
(1) Given you're already setting the number as the text of the button, use that within the handler like this:
// jQuery will set 'this' for you when it calls your click handler
[...].click(function(){ alert($(this).text()); });
(2) Create a closure so that the individual values of num
are retained for each handler:
[...].click((function(closureNum){
return function(){ alert(closureNum); }
})(num));
EDIT: Just saw the other answers. For a better variation on my second option I would remend doing what T.J. and FishBasketGordo did and have a separate handler building function rather than doing it inline like I did. Either should work, but the separate handler builder should be more efficient (and, arguably, easier to read).
Try this
<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(nums[i]);});
$('#nums').append(btn);
}
</script>
This is simpler:
var nums = [1,2,3,4,5];
$.each(nums, function(index, value){
var btn=$('<button></button>').text(value).click(function(){alert(value);});
$('#nums').append(btn);
});
As you already have jquery in your page, why not use $.each()?
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744766246a4592480.html
评论列表(0条)