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

Javascript loop variable registers dom events - powerful closure_javascript skills

WBOY
WBOYOriginal
2016-05-16 18:20:061091browse

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...)
Statement:
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