$(this)在ajax调用后未定义

问题描述:

我正在做一个ajax请求,点击一个ID为href的锚点标签。顺便说一下,这个锚标签是动态创建的。

<a href="983" class="commentDeleteLink">delete</a> 

当锚标记被点击下面的代码被执行:

$('.commentDeleteLink').live('click', function(event) { 
     event.preventDefault(); 
     var result = confirm('Proceed?'); 

     if (result) { 
      $.ajax({ 
       url: window.config.AJAX_REQUEST, 
       type: "POST", 
       data: { action  : 'DELCOMMENT', 
         comment  : $('#commentText').val(), 
         comment_id : $(this).attr('href') }, 
       success: function(result) { 
        alert($(this).attr('href')); 
        //$(this).fadeOut(slow); 
       } 
      }); 
     } 
    }); 

当我试图显示$(本).attr( 'href' 属性),它说,这是 “不确定”。我真正想做的是淡入淡出,但当我调查$(this)的值时,它是“未定义的”。

上面的代码片段有什么问题?

+0

成功处理程序中的'this'是处理成功的函数,而不是您点击触发ajax请求的原始html元素。一个函数没有'href'属性。 – 2012-03-22 17:23:42

+0

[jquery AJAX调用:$(this)可能重复在成功后不起作用](http://stackoverflow.com/questions/1392789/jquery-ajax-call-this-does-not-work-after-success) – JJJ 2012-03-22 17:24:26

+0

[Ajax jQuery成功范围]的可能重复(http://stackoverflow.com/questions/1570146/ajax-jquery-success-scope) – 2012-03-22 17:24:52

你应该尝试

$('.commentDeleteLink').live('click', function(event) { 
    event.preventDefault(); 
    var result = confirm('Proceed?'); 
    var that = this; 
    if (result) { 
     $.ajax({ 
      url: window.config.AJAX_REQUEST, 
      type: "POST", 
      data: { action  : 'DELCOMMENT', 
        comment  : $('#commentText').val(), 
        comment_id : $(this).attr('href') }, 
      success: function(result) { 
       alert($(that).attr('href')); 
       //$(that).fadeOut(slow); 
      } 
     }); 
    } 
}); 

因为回调而不是点击的元素,你应该缓存this在一个变量that,你可以重新使用,而不是this对上下文敏感

+0

不知道这个存在!谢谢你! :d – JohnnyQ 2012-03-22 17:33:43

$(this)在函数内部被调用。这里是修复:

$('.commentDeleteLink').live('click', function(event) { 
    var myRef = this; 

    event.preventDefault(); 
    var result = confirm('Proceed?'); 

    if (result) { 
     $.ajax({ 
      url: window.config.AJAX_REQUEST, 
      type: "POST", 
      data: { action  : 'DELCOMMENT', 
        comment  : $('#commentText').val(), 
        comment_id : $(this).attr('href') }, 
      success: function(result) { 
       alert($(myRef).attr('href')); 
       //$(this).fadeOut(slow); 
      } 
     }); 
    } 
}); 

您处于AJAX功能中,因此如果要使用$(this) th,则必须先将点击功能的$(this)分配给变量ERE

$('.commentDeleteLink').live('click', function(event) { 
    .... 
    var current = $(this); 
    $.ajax({ 
     // You can use current here 
    }); 
}); 

click事件处理(即this是指在处理程序的对象)的情况下不会传播到你的AJAX成功回调。

您可以通过将其分配到一个局部变量捕捉this来自来电的价值,或者你可以明确地在context选项$.ajax()传递this它传播:

$.ajax({ 
    url: window.config.AJAX_REQUEST, 
    type: "POST", 
    data: { 
     action: "DELCOMMENT", 
     comment: $("#commentText").val(), 
     comment_id: $(this).attr("href") 
    }, 
    context: this, 
    success: function(result) { 
     $(this).fadeOut("slow"); // Works, since 'this' was propagated here. 
    } 
}); 

范围变更的函数内。

缓存链接对象并在ajax请求中引用它。