jQuery的阿贾克斯成功处理程序访问该 [英] Accessing this in jquery ajax success handler

查看:99
本文介绍了jQuery的阿贾克斯成功处理程序访问该的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  //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,它工作正常。我怎样才能做到这一点一旦请求已成功?

In the success handler, I'm attempting to change the html of the clicked element from Save to Edit. If I place this directly below the click handler for .save_cat, it works fine. How can I do this once the request has been successful?

推荐答案

您需要捕获它的价值在一个局部变量的生活处理程序。

You need to capture its value in a variable local to the live handler.

$('.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 是preferred < /一>在 .live 在jQuery和LT; 1.7, 。对是preferred jQuery中1.7+] 2

FWIW, .delegate is preferred over .live in jQuery < 1.7, and .on is preferred in jQuery 1.7+]2.

这篇关于jQuery的阿贾克斯成功处理程序访问该的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆