Work a few days ago to write the front-end JS code, encountered a traversal element to add click events to it. This is the question that has kept me tuned for a whole afternoon. Finally, go home from work, the Internet to find out how to solve the information. PS: Before the fourth edition of the jquery Basics tutorial, I read about the contents of the cyclic binding process, and I didn't think much of it, so I didn't remember it. )
If the great God knew this kind of situation, can turn off the window, writes these mainly is gives like me the small white to look. Thank you!
Let's take a look at the wrong example first. (use jquery in the example, please import jquery library)
Loop binding handler
button 1
< Button id= "btn2" > button 2
button 3
Button 4
After this code is run, click on the button, the pop-up alert shows the data a few, I always thought the button 1 to button 4, corresponding to the number of alert is 1 to 4. If you think so too, that's wrong.
Click each button, alert is displayed in the number 4, did not think it!
Now write several solutions, a total of reference!
The first, write a function, in which the functions are returned.
Second, use immediate call function expression
(function (value) {
code block
}) (i)//This is the immediate invocation of a function expression
the third, each function that uses jquery
Using the above three kinds of situations, you can avoid the situation in the beginning.
where get (0) refers to converting a jquery object to a DOM object.