jQuery ajax loop and iteration scope

前端 未结 4 732
终归单人心
终归单人心 2021-01-25 23:07

I\'m wondering why in the code below the i variable still shows \"5\" instead of showing \"1\" then \"2\" the

4条回答
  •  攒了一身酷
    2021-01-25 23:32

    Solution using Function#bind():
    http://jsfiddle.net/RQncd/1/

    for (var i = 0; i < 5; i++) {   
      $.ajax({
        url: '/echo/html/',
        method:'post',
        data: {
          html: 'Ajax data'
        },
        success: (function (i, resp) {
          $('#success').append(i);
        }).bind(null, i)
      });
      $('#outsideAjax').append(i);
    }
    

提交回复
热议问题