成功后如何访问$(this)的值:使用jquery时的function()?无论我尝试过什么,似乎我都无法做到。
$('.add').click(function() {
//etc etc
$.ajax({
type:"GET",
url:"/",
data:data,
dataType: 'json',
beforeSend:function(html){
//Nothing here right now
},
success: function(){
$(this).parent("div").after("<div class='flag'>I'm the new one.</div>");
},
<div id="container">
<div class="h1" data-id="1">Teachers <span class="add" data-id="US01">Add New</span></span>
</div>
<div class="flag">Flag</div>
<div class="edit">Edit</div>
<div class="h2" data-id="2">Who is your favorite Math teacher? <span class="add" data-id="US02">Add New</span></div>
<div class="flag">Flag</div>
<div class="edit">Edit</div>
<br>
<div class="h1" data-id="8">Restaurants <span class="add" data-id="US10">Add New</span></div>
<div class="flag">Flag</div>
<div class="edit">Edit</div>
<div class="h2" data-id="9">Which is your favourtie restaurant in town? <span class="add" data-id="US20">Add New</span></div>
<div class="flag">Flag</div>
<div class="edit">Edit</div>
</div>
答案 0 :(得分:4)
在进行ajax调用之前将this
保存到变量并改为使用它:
$('.add').click(function() {
var self = this; // save this as self
//etc etc
$.ajax({
type:"GET",
url:"/",
data:data,
dataType: 'json',
beforeSend:function(html){
//Nothing here right now
},
success: function(){
// use self instead of this
$(self).parent("div").after("<div class='flag'>I'm the new one.</div>");
},
答案 1 :(得分:3)
&#34;这&#34;在你的阿贾克斯内部成功是不一样的&#34;这个&#34;外部。
不同的范围......
这个问题有一个很好的解决方案。
$('.add').click(function() {
var that = $(this);
//do whatever you want :]
$.ajax({
type:"GET",
url:"/",
data:data,
dataType: 'json',
beforeSend:function(html){
//Nothing here right now
},
success: function(){
that.parent("div").after("<div class='flag'>I'm the new one.</div>");
},
});
});
答案 2 :(得分:0)
这是范围问题。您需要将this
分配给可访问范围内的变量。然后在子函数中使用该变量。
注意我已使用_that
这应该有效,如果没有,请发表评论。
$('.add').click(function() {
var _that = this;
$.ajax({
type:"GET",
url:"/",
data:data,
dataType: 'json',
beforeSend:function(html){
//Nothing here right now
},
success: function(){
$(_that).parent("div").after("<div class='flag'>I'm the new one.</div>");
},
});
});