简体   繁体   中英

javarscript “mutable variable is accesible from closure” in loop

Im trying to assign a function to every button inside an array.

to simplify the problem i have exchanged the functionality of that function with a simple console.log

When one of the buttons is clicked the console is supposed to say "button number" and then the according button number (1, 2, 3...) Instead it always returns the maximum button number.

        function buttoncount(){
            dbuttons = document.getElementsByClassName("deletebutton");
            for(var ii = 0; ii< dbuttons.length; ii++){
                dbuttons[ii].onclick = function (){
                    console.log("button number"+ii);
                }
            }
        }

thanks in advance

You'd have to ensure that separate closures are caught for consecutive buttons. One of the ways is always to wrap the actual function within another one that is immediately executed.

    function buttoncount(){
        dbuttons = document.getElementsByClassName("deletebutton");
        for(var ii = 0; ii< dbuttons.length; ii++){
            dbuttons[ii].onclick = (function (x){
                return function() {
                  console.log("button number"+x);
                }
            }(ii));
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM