Javascript function is using the last known parameters in loop?

前端 未结 3 444
后悔当初
后悔当初 2020-12-20 07:30

I have a situation whereby, i need to create buttons dynamically and i need to attached an onclick event to each of them. All of the above is done fine. However, when one o

3条回答
  •  北荒
    北荒 (楼主)
    2020-12-20 07:57

    You can use jQuery proxy

    var buttons = $("a");
    for (var i = 0; i < buttons.length; i++){
      $(buttons[i]).unbind("click").click(
        $.proxy(
          function(){
            alert(this);
            return false;
          },
          i
        )
      );
    }
    

    or capture your arguments by creating new function

    var buttons = $("a");
    for (var i = 0; i < buttons.length; i++){
      $(buttons[i]).unbind("click").click(
        function(arg){
          return function(){
            alert(arg);
            return false;
          };
        }(i)
      );
    }
    

    Just run one of this examples in firebug console to see the effect.

提交回复
热议问题