Closures in a for loop

后端 未结 5 1981
温柔的废话
温柔的废话 2020-11-27 07:05

Closures in a loop are causing me problems. I think I have to make another function that returns a function to solve the problem, but I can\'t get it to work with my jQuery

5条回答
  •  甜味超标
    2020-11-27 07:28

    @Andy solution is the nicest. But you can also use Javascript scoping to help you save the value in your closure.

    You do so by creating a new scope in your loop body by executing an anonymous function.

    for (var i = 0; i < 3; i++) {
      (function(){
        var index = i; 
        $('#button'+index).click(function(){
          foo(index);
        });
      })();
    }
    

    Since the loop body is a new scope at each iteration, the index variable is duplicated with the correct value at each iteration.

提交回复
热议问题