开发者

AJAX Closures and targeting 'this'

In the code example below the success callback function logs 'input#04.update' four times rather than each individual input, which ma开发者_如何学Pythonkes sense seeing how closures work but how would I go about targeting each individual input using this.

<input type="text" name="" id="01" class="update">
<input type="text" name="" id="02" class="update">
<input type="text" name="" id="03" class="update">
<input type="text" name="" id="04" class="update">

function updateFields(){
 $('input.update').each(function(){
    $this = $(this);
    $.ajax({
      data: 'id=' + this.id,
      success: function(resp){
       console.log($this);
          $this.val(resp)
      }
    });
  });
}


You forgot var

var $this = $(this);

Don't forget var. One programmer who forgot var went to bed at night and woke up to find his apartment on fire. He added var and the fire went out. Another programmer left var out completely shortly before leaving on a business trip to Europe. The airplane developed in-flight mechanical problems shortly after takeoff, causing the pilot to initiate emergency landing procedures. From his laptop the programmer quickly added var and the plane made it safely to an airport.

Don't forget var. If you put var in your code, you'll meet somebody special today. Try it. It sounds amazing but it really works!


Pointy's correct on var usage, another alternative is to use $.proxy(), like this:

function updateFields(){
 $('input.update').each(function(){
    $.ajax({
      data: 'id=' + this.id,
      success: $.proxy(function(resp){
                 $(this).val(resp);
               }, this)
    });
  });
}

This closure creator will make this refer to the input element when you're inside the success callback, which is usually what you're after...so I'm not sure why this isn't the case by default, but in any case $.proxy() rectifies the situation.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜