Simple implementation code of JavaScript dynamic binding event

Source: Internet
Author: User

Below is the DOM structure of the page CopyCode The Code is as follows: <ul id = "test">
<Li> one </LI>
<Li> two </LI>
<Li> three </LI>
<Li> four </LI>
</Ul>

Below is the JavaScript codeCopy codeThe Code is as follows: // obtain an object by ID
Function ID (v) {return document. getelementbyid (V );}

// Obtain Objects Based on tags
Function tag (element, T) {return element. getelementsbytagname (t );}

Window. onload = function (){
// Obtain all Li objects under test
VaR li = tag (ID ("test"), "Li ");

// Bind the mouse to the event cyclically
For (VAR I = 0; I <li. length; I ++ ){
Li [I]. onclick = function (){
// Expected pop-up: 1, 2, 3, 4
// The result is always 5
Alert ("the number you clicked" + (I + 1) + "item ");
}
}
}

Why is the above image displayed? The reason is that "event binding in for is not executed immediately ". The modified code is as follows:Copy codeThe Code is as follows: // obtain an object by ID
Function ID (v) {return document. getelementbyid (V );}

// Obtain Objects Based on tags
Function tag (element, T) {return element. getelementsbytagname (t );}

Window. onload = function (){
// Obtain all Li objects under test
VaR li = tag (ID ("test"), "Li ");

// Bind the mouse to the event cyclically
For (VAR I = 0; I <li. length; I ++ ){
(Function (){
VaR T = I
Li [I]. onclick = function (){
Alert ("You clicked item" + T + ");
}
})();
}
}

Test code. Everything is OK. we normally upload the Circular Variable I to the processing function corresponding to the onclick event.

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.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.