Talk about loop binding handlers in JS closures
- 2020-03-30 04:17:03
- OfStack
A few days ago when I was writing front-end js code at work, I encountered the traversal element to add a click event to it. That's the question that kept me tuned all afternoon. Finally or go home from work, look up information on the Internet just know how to solve. (PS: I also read about the circular binding handler in the fourth edition of jQuery foundation tutorial, and I don't remember it because I didn't pay much attention to it.)
If the big god knows this kind of situation, can close the window, write these mainly for the small white white like me to see. Thank you very much!
So I'm going to stick up the wrong example for you to see. (jQuery is used in the example, please import jQuery library)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title> Loop binding handler </title>
<script src="js/jquery-2.1.1.min.js"></script>
<script type="text/javascript">
$(function(){
for(var i=1;i<=4;i++){
$("#btn"+i).get(0).onclick=function(){
alert(i);
}
}
});
</script>
</head>
<body>
<button id="btn1"> button 1</button>
<button id="btn2"> button 2</button>
<button id="btn3"> button 3</button>
<button id="btn4"> button 4</button>
</body>
</html>
When this code runs, you click on the button, and the alert pops up, and I've been thinking of buttons 1 through 4, and the number in the alert is also 1 through 4. If you think so, you are wrong.
Click on each button, and the number 4 will appear in alert.
Write a few kinds of solution now, consult in all!
First, write a function that returns a function
<script type="text/javascript">
$(function(){
for(var i=1;i<=4;i++){
$("#btn"+i).get(0).onclick=btnClick(i);
}
});
var btnClick=function(value){
return function(){
alert(value);
}
}
</script>
Second, use the immediate call function expression
(function (value) {
/ / code block
})(I)// this is the immediate call to the function expression
<script type="text/javascript">
$(function(){
for(var i=1;i<=4;i++){
$("#btn"+i).get(0).onclick=(function(value){
return function(){
alert(value);
} })(i);
}
});
</script>
Third, use jQuery's each function
<script type="text/javascript">
$(function(){
$.each([1,2,3,4],function(index,value){
$("#btn"+value).get(0).onclick=function(){
alert(value);
}
});
});
</script>
By using all three of the above, you can avoid the first situation.
Where get(0) refers to converting jQuery objects into DOM objects.