admin管理员组文章数量:1355721
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
2 Answers
Reset to default 12You 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.
本文标签:
版权声明:本文标题:javascript - AJAX Closures and targeting 'this' - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1743959934a2568835.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论