2011-11-30 51 views
0
//Save new category information 
    $('.save_cat').live('click', function() { 

     cat_id = $(this).attr("id").slice(4); 
     cat_name = $(this).parent().prev().prev().children('.cat_name_edit').val(); 
     sort_order = $(this).parent().prev().children('.sort_order_edit').val(); 

     $.ajax({ type: 'POST', 
       url: '../file/category/update_category', 
       data: { 'cat_id' : cat_id, 
         'sort_order' : sort_order, 
         'cat_name' : cat_name}, 
       beforeSend:function(){ 

        //action while loading 

       }, 
       success:function(data){ 

        alert('hi'); 
        $(this).html("Edit"); 

       }, 
       error:function(){ 

        // failed request; give feedback to user 
        alert("An unexpected error has occurred. Your category could not be saved."); 
       }, 

       dataType : 'json' 
     }); 
    }); 

在成功處理程序中,我試圖將單擊元素的html從「保存」更改爲「編輯」。如果我把它放在.save_cat的點擊處理程序的正下方,它可以正常工作。一旦請求成功,我怎麼能做到這一點?在jquery ajax成功處理程序中訪問此內容

回答

6

您需要在live處理程序的本地變量中捕獲其值。

$('.save_cat').live('click', function() { 
    var $that = $(this); 

    // These should be vars. 
    var cat_id = $that.attr("id").slice(4); 
    ... 
    $.ajax({ ... 
     success: function() { $that.html("Edit"); } 

FWIW,.delegate is preferred超過.live jQuery中< 1.7,.on is preferred jQuery中1.7+] 2

+0

謝謝,這就是我正在尋找的:) – ThinkingInBits

+0

活處理程序的第一行應該是'var element = $(this);'然後在你的'success'處理程序中操作變量'element'。 – MilkyWayJoe