Solve the problem of bulk add events in JavaScript

Source: Internet
Author: User

This is a commonplace problem in JavaScript and a difficult question for beginners to understand. When adding events to a series of elements, there are often some problems that we do not want to appear. For example, the following code:

// Batch Add click event to li element function () {    var lists = document.getElementsByTagName ("li");      for (var i=0;i<lists.length;i++) {        function() {            alert (i);     }}}

Here we expect to return its index when the Li element is clicked. Unfortunately, each click Returns a value of Lists.length.

What is the reason? When the page onload finishes, the for loop is executed immediately. The global variable I immediately gets the final value lists.length, when an LI element is triggered by the click event, the code in the anonymous function is executed, and the code looks up for I along the scope chain, and the result can only find global variables. At this point, the occurrence has already occurred, I was not the original index I, but the for loop after the completion of the final value.

There are many ways to solve this problem. The most common method is to create a closure. The code is as follows:

function () {    var lists = document.getElementsByTagName ("li");      for (var i=0;i<lists.length;i++) {        = (function(num) {            return  function() {                alert (num);            }        }) (i);    }}

Here's a much easier way to understand the code as follows:

function () {    var lists = document.getElementsByTagName ("li");      for (var i=0;i<lists.length;i++) {        = i;         function () {            alert (this. index);     }}}

Solve the problem of bulk add events in JavaScript

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.