简体   繁体   English

循环中的javarscript“可变变量可以从闭包中获取”

[英]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 为了简化问题,我已经用一个简单的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. 单击一个按钮时,控制台应该说“按钮号”,然后说相应的按钮号(1、2、3 ...),而是总是返回最大按钮号。

        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));
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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