2011-11-30 84 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

相关问题