Strange things in JavaScript “for”

后端 未结 6 1402
误落风尘
误落风尘 2020-12-19 05:07

I\'m using jQuery and I have a strange thing that I don\'t understand. I have some code:

for (i = 1; i <= some_number; i++) {
    $(\"#some_button\" + i).         


        
6条回答
  •  自闭症患者
    2020-12-19 05:53

    It has to do with JavaScript scoping. You can get around it easily by introducing another scope by adding a function and having that function call itself and pass in i:

    for (var i = 1; i <= some_number; i++) {
      (function(j) {
        $("#some_button" + j).click(function() {
          alert(j);
        });
      })(i);
    }
    

    This creates a closure - when the inner function has access to a scope that no longer exists when the function is called. See this article on the MDC for more information.

    EDIT: RE: Self-calling functions: A self-calling function is a function that calls itself anonymously. You don't instantiate it nor do you assign it to a variable. It takes the following form (note the opening parens):

    (function(args) {
      // function body that might modify args
    })(args_to_pass_in);
    

    Relating this to the question, the body of the anonymous function would be:

    $("#some_button" + j).click(function() {
      alert(j);
    });
    

    Combining these together, we get the answer in the first code block. The anonymous self-calling function is expecting an argument called j. It looks for any element with an id of some_button with the integer value of j at the end (e.g. some_button1, some_button10). Any time one of these elements is clicked, it alerts the value of j. The second-to-last line of the solution passes in the value i, which is the loop counter where the anonymous self-calling function is called. Done another way, it might look like this:

    var innerFunction = function(j) {
      $("#some_button" + j).click(function() {
        alert(j);
      });
    };
    
    for (var i = 1; i <= some_number; i++) {
      innerFunction(i);
    }
    

提交回复
热议问题