成功后访问$(this):使用$ .ajax时的function()

成功后如何访问$(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("
I'm the new one.
"); },
Teachers Add New
Flag
Edit
Who is your favorite Math teacher? Add New
Flag
Edit

Restaurants Add New
Flag
Edit
Which is your favourtie restaurant in town? Add New
Flag
Edit

在进行ajax调用之前将其保存到变量并使用它:

 $('.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("
I'm the new one.
"); },

你的ajax成功中的“这个”与外面的“这个”不一样。

不同的范围……

这个问题有一个很好的解决方案。

 $('.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("
I'm the new one.
"); }, }); });

这是范围问题。 您需要将其分配给可访问范围内的变量。 然后在子函数中使用该变量。

注意我已经使用了_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("
I'm the new one.
"); }, }); });