最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - AJAX Closures and targeting 'this' - Stack Overflow

programmeradmin3浏览0评论

In the code example below the success callback function logs 'input#04.update' four times rather than each individual input, which makes 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)
      }
    });
  });
}

In the code example below the success callback function logs 'input#04.update' four times rather than each individual input, which makes 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)
      }
    });
  });
}
Share Improve this question asked Jun 11, 2010 at 13:45 screenm0nkeyscreenm0nkey 18.9k18 gold badges62 silver badges75 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 12

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 pletely 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)

  1. 暂无评论