成功后访问$(this):使用$ .ajax时使用function() [英] Accessing $(this) after success:function() when using $.ajax
本文介绍了成功后访问$(this):使用$ .ajax时使用function()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
使用jquery后,如何访问$(this)的值:function()?不管我尝试了什么,看来我都做不到.
How can I access the value of $(this) after success: function() when using jquery? No matter what I've tried, it appears I cant do it.
$('.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>
推荐答案
在进行ajax调用之前将this
保存到变量中,并使用该变量:
Save this
to a variable before making the ajax call and use that instead:
$('.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>");
},
这篇关于成功后访问$(this):使用$ .ajax时使用function()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文