AJAX闭包和定位'这个' [英] AJAX Closures and targeting 'this'

查看:85
本文介绍了AJAX闭包和定位'这个'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的代码示例中,成功回调函数将'input#04.update'记录四次而不是每个单独的输入,这有助于了解闭包是如何工作的,但我将如何使用它来定位每个单独的输入。

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)
      }
    });
  });
}


推荐答案

你忘了 var

var $this = $(this);

不要忘记 var 。一位忘了 var 的程序员晚上睡觉,醒来发现他的公寓着火了。他添加了 var ,火灾就消​​失了。另一位程序员在出差到欧洲之前不久就完全离开 var out 。飞机起飞后不久飞机发生飞行中的机械问题,导致飞行员启动紧急着陆程序。程序员从他的笔记本电脑上快速添加 var ,然后飞机安全地到达机场。

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.

不要忘记 VAR 。如果你在代码中加上 var ,你会遇到一个特别的今天。试试吧。这听起来很棒,但确实有效!

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!

这篇关于AJAX闭包和定位'这个'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆