Closures in a for loop

后端 未结 5 1983
温柔的废话
温柔的废话 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:32

    Or just manufacture a new function, as you describe. It would look like this:

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

    I'm pretty sure Mehrdad's solution doesn't work. When you see people copying to a temporary variable, it's usually to save the value of "this" which may be different within an inner child scope.

提交回复
热议问题