2012-09-22 50 views
1

我有一個jQuery腳本,其中我將在刪除該記錄後隱藏div。 這裏是jQuery。隱藏div在jQuery Ajax成功中無法正常工作

$(document).ready(function() { 
    $(".deleteComment").click(function() 
    { 
     alert("asd"); 

     var Id = $(this).attr("id"); 

     var url1 = "@Html.Raw(Url.Action("DeleteComment", "Comment", new { id = "idValue" }))"; 
     url1=url1.replace("idValue",Id); 
     alert(url1); 

     $.ajax(
     { 
      type: 'post', 
      url: '/Comment/DeleteComment', 
      dataType: 'json', 
      data: 
      { 
       'EId' : Id  
      }, 
      success: function (data) 
      { 
       alert ("Hello"); 
       var commentBlock = $(this).closest('div'); 
       commentBlock.hide('slow');         
      }     
     }); 

問題只是在下面的代碼:

success: function (data) 
{ 
    alert ("Hello"); 
    var commentBlock = $(this).closest('div'); 
    commentBlock.hide('slow'); 
} 

如果我把上面的代碼在腳本的開頭,然後它工作正常。如果我投入成功,那就失敗了。

+0

你有什麼錯誤嗎? – MikkoP

+0

否..它只是不工作...如果我把代碼放在開始然後它完美工作... – user1668543

+0

成功回調中的「this」處理ajax對象。所以你需要聲明類似「var self = this;」,然後在ajax調用中使用$(self).closest等等。 –

回答

3

this將引用agor對象,如伊戈爾提到的,他的意思是這樣的。

$(document).ready(function()) { 
    var self = this; 

    ... 
    $.ajax(
     ... 

     success: function(data) { 
      $(self).closest("div").hide("slow"); 
     } 
    ); 
} 
+0

非常感謝...這工作... – user1668543

+0

謝謝@MikkoP,正是我的意思! –