2

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>
4

3 回答 3

4

this在进行 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("<div class='flag'>I'm the new one.</div>");
            },
于 2013-09-06T14:30:15.070 回答
3

你的ajax成功里面的“this”与外面的“this”不一样。

不同的范围...

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

$('.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>");
        },

  });
});
于 2013-09-06T14:33:09.327 回答
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>");
        },
    });
 });
于 2013-09-06T14:33:24.280 回答