Home > Web Front-end > JS Tutorial > The problem of setting anonymous function for button loop in js

The problem of setting anonymous function for button loop in js

小云云
Release: 2017-12-06 15:09:48
Original
1560 people have browsed it

I wanted to set up listening events for the button loop, but only the last button responded, or an error was reported directly undefined. This is the original wrong way of writing, set an anonymous function for the button num_jia's onclick, in the anonymous function i will use for at the end of the loop, which is 3, so undefined error will be reported. function a(){

for(var i=0;i<3;i++) {

num_jia[i] = document.getElementsByClassName('num-jia')[i];

num_jia[i].onclick = function () {

alert(num_jia[i])

         }

}

}

I checked online and found that if you want anonymous functions to remember their respective i, you only need to use the appropriate closure Packages (functions that can access independent data), the following are improvements, please learn the specific knowledge about closures on your own.

function a(){

for(var i=0;i<3;i++) {

num_jia[i] = document. getElementsByClassName('num-jia')[i];

;(function (i2) {

num_jia[i2].onclick = function () {

                   num_jia[i2])

        }

         })(i);

}

}

I later researched and found that there is actually a complete way to write a famous function, which achieves the same effect and is easy to understand.

function a(){

for (var i=0;i<3;i++) {

num_jia[i] = document.getElementsByClassName('num-jia')[i];

doThings(i);

}

}

functiondoThings(i){

num_jia[i2].onclick= function () {

              alert(num_jia[i2])

}

}

The above content is the problem of setting anonymous functions for button loops in js. I hope it can help everyone. .

Related recommendations:

JS button color switching effect implementation example

JS button implementation code for adding background music

How is the JS button flashing function implemented?

The above is the detailed content of The problem of setting anonymous function for button loop in js. For more information, please follow other related articles on the PHP Chinese website!

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