AddEventListener problems with loop binding

Source: Internet
Author: User

Today I have a problem with this code as follows

  var someth = document.getElementsByTagName ("a");            for (var i = 0; i < i++) {                someth[i].addeventlistener ("click", Function () {alert (i)})            }

Found the problem, every time alert out of the same value 10 found on the Internet to find the original result of the closure of the packet.

I'll just stick to two solutions here.

Method One: Give Someth[i a property at the time of the loop, so that the value of alert out of I will change.

var someth= document.getelementsbytagname ("a");            for (var i = 0; I <10; i++) {                someth[i].num = i;                Someth[i].onclick = function () {                                       alert (this.num);                }            }

Method Two: A function is nested outside the function.

var someth = document.getElementsByTagName ("a"); for (var i = 0; i <; i++) {                someth[i].addeventlistener ("click", (function (num) {                    return function () {                                                alert ("I am link" + num);                    }                }) (i), "false");            }

PS: Attach the information I read http://segmentfault.com/q/1010000000626710

AddEventListener problems with loop binding

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.