Home > Web Front-end > JS Tutorial > body text

Javascript loop variable registers dom events - powerful closure_javascript skills

WBOY
Release: 2016-05-16 18:20:06
Original
1107 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!