SoFunction
Updated on 2025-04-03

A brief discussion on loop binding handler in JS closure

A few days ago, when I was writing front-end js code at work, I encountered a traversal element and added a click event to it. It was this problem that made me adjust it all afternoon. Finally, I went home from get off work and searched the information online to find out how to solve it. (PS: I also read the content of loop binding processing programs in the fourth edition of "JQuery Basic Tutorial". I guess I didn't read it carefully at the time, so I didn't remember it.)
If the great master knows this kind of situation, he can close the window and write these mainly for newbie like me. Thanks!

Let’s post the wrong examples first for everyone to see. (JQuery is used in the example, please import the jQuery library)

Copy the codeThe code is as follows:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http:///TR/xhtml1/DTD/">
<html xmlns="http:///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."></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 >Button 1</button>
<button >Button 2</button>
<button >Button 3</button>
<button >Button 4</button>
</body>
</html>

 
After this code is run, click the button and the data displayed in the pop-up alert is displayed. I have always thought that buttons 1 to 4, and the corresponding numbers in the alert are also 1 to 4. If you think so, you're wrong.
Click each button and the number 4 is displayed in the alert. I didn’t expect it!
Now write a few solutions for your reference!
The first type is to write a function, and return a function in this function

Copy the codeThe code is as follows:

<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>

The second type: use the call function expression immediately
(function(value){
//Code block
})(i)//This is to call the function expression immediately

Copy the codeThe code is as follows:

<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>

The third type, each function using jQuery

Copy the codeThe code is as follows:

<script type="text/javascript">
$(function(){
$.each([1,2,3,4],function(index,value){
$("#btn"+value).get(0).onclick=function(){
alert(value);
}
});
});
</script>

Using the above three situations can avoid that situation at the beginning.
where get(0) refers to converting a jQuery object into a DOM object.

The above is my personal understanding of the loop binding handler in JS closure. I will share it with you. I hope it will be helpful to my friends.