Home > Web Front-end > JS Tutorial > Javascript loop variable registers dom events - powerful closure_javascript skills

Javascript loop variable registers dom events - powerful closure_javascript skills

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2016-05-16 18:20:06
Original
1180 people have browsed it

Encountered this problem today:

Copy code The code is as follows:

//pseudocode
for (var i=0; iaddEvent(obj[i], "click", func(i));
}

The result appears The problem was solved. All DOM events were registered when i=n. After checking some information, it was said that this was changed during the loop process, and the registered events were also changed accordingly. I found a solution;

Copy code The code is as follows:

for (var i=0; i< n; i ) {
(function (i){addEvent(obj[i], "click", function (){func(i);});})(i);
}

Use bipack to maintain persistent references to variables, very powerful!
(If you have a better method, please feel free to enlighten me (*^__^*) Heehee...)
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Issues
What are JavaScript hook functions?
From 1970-01-01 08:00:00
0
0
0
What is JavaScript garbage collection?
From 1970-01-01 08:00:00
0
0
0
c++ calls javascript
From 1970-01-01 08:00:00
0
0
0
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template