2012-03-22 55 views
2

我正在做一個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

回答

1

你應該嘗試

$('.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

1

$(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); 
      } 
     }); 
    } 
}); 
0

您處於AJAX功能中,因此如果要使用$(this) th,則必須先將點擊功能的$(this)分配給變量ERE

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

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. 
    } 
}); 
0

範圍變更的函數內。

緩存鏈接對象並在ajax請求中引用它。