JavaScript Dynamic binding event simple implementation code _javascript tips

Source: Internet
Author: User
The following is the DOM structure of the page
Copy Code code as follows:

<ul id= "Test" >
<li>One</li>
<li>Two</li>
<li>Three</li>
<li>Four</li>
</ul>

Here is the JavaScript code
Copy Code code as follows:

Get an object from an ID
function ID (v) {return document.getElementById (v);}

Get objects from tags
function tag (element, T) {return element.getelementsbytagname (t);}

Window.onload = function () {
Get all of the Li objects under test
var li = tag (ID ("test"), "Li");

Loop-bound Mouse click event
for (var i=0; i<li.length; i++) {
Li[i].onclick = function () {
Expect pop-up 1,2,3,4
The result pops up always 5
Alert ("You clicked the first" + (i+1) + "item");
}
}
}

Why is there the image above? The reason is "the event bindings in for are not immediately executed." The modified code is as follows:
Copy Code code as follows:

Get an object from an ID
function ID (v) {return document.getElementById (v);}

Get objects from tags
function tag (element, T) {return element.getelementsbytagname (t);}

Window.onload = function () {
Get all of the Li objects under test
var li = tag (ID ("test"), "Li");

Loop-bound Mouse click event
for (var i=0; i<li.length; i++) {
(function () {
var t = i
Li[i].onclick = function () {
Alert ("You clicked the first" + t + "item");
}
})();
}
}

Test code, everything OK, we normally pass the loop variable i to the OnClick event corresponding to the handler function.

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.