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