Simple implementation of Javascript dynamic binding events-javascript tips-js tutorial

Source: Internet
Author: User
There are many methods for binding Javascript events, which are flexible. However, as a relatively simple dynamic binding, the following code seems correct, but cannot achieve the expected results. Below is the dom structure of the page

The Code is as follows:



  • One

  • Two

  • Three

  • Four



Below is the javascript code

The Code is as follows:


// Obtain the 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 [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:

The Code is as follows:


// Obtain the 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 (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.
Related Article

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.