Home > Web Front-end > JS Tutorial > A brief discussion on the loop binding handler in JS closure_Basic knowledge

A brief discussion on the loop binding handler in JS closure_Basic knowledge

WBOY
Release: 2016-05-16 16:31:48
Original
1449 people have browsed it

When I was writing front-end js code at work a few days ago, I encountered the problem of traversing elements and adding click events to them. It was this question that kept me tuned for an entire afternoon. In the end, I went home from get off work and looked up information online to find out how to solve the problem. (PS: I also read about loop binding handlers in the fourth edition of "JQuery Basics Tutorial" before. I probably didn't pay much attention to it at the time, so I didn't remember it.)
If the master knows about this kind of situation, you can close the window. I write this mainly for novices like me. Thanks!

First post the error example for everyone to see. (jQuery is used in the example, please import the jQuery library)

Copy code The code is as follows:

http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" >
http://www.w3.org/1999/xhtml">


Loop binding handler












After this code is run, click the button, and the pop-up alert displays the number of data. 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 are wrong.
When you click each button, the number 4 is displayed in the alert. I didn’t expect it!
Now I will write down several solutions for your reference!
The first method is to write a function and return a function in this function

Copy code The code is as follows:


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

Copy code The code is as follows:


The third method is to use jQuery’s each function

Copy code The code is as follows:


Using the above three situations, you can avoid the situation at the beginning.
Among them, get(0) refers to converting the jQuery object into a DOM object.

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

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template