A cyclic binding handler in JS closure

Source: Internet
Author: User
Tags object closure expression return jquery library

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.



Related Article

Alibaba Cloud 10 Year Anniversary

With You, We are Shaping a Digital World, 2009-2019

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.