Strange things in JavaScript “for”

后端 未结 6 1404
误落风尘
误落风尘 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:41

    This is because of how closures work in JavaScript. Each of the 5 functions you are creating is basically sharing the same i variable. The value of i inside your function is not being evaluated when you are creating the function, but when the click event occurs, by which time the value of i is 5.

    There are various techniques for getting around this (when this behavior isn't what you want). One (if you have a simple function, like you do here) is to use the Function constructor instead of a function literal:

    $("#some_button" + i).click(new Function("alert("+i+")");
    

提交回复
热议问题