Jquery AJAX调用:$(this)在成功后不起作用

Sco*_* UX 3 ajax jquery this

我想知道为什么$(this)在jQuery ajax调用之后不起作用.

我的代码是这样的.

$('.agree').live("click", function(){  // use live for binding of ajax results
      var id=($(this).attr('comment_id'));
      $.ajax({
        type: "POST",
        url: "includes/ajax.php?request=agree&id="+id,
        success: function(response) {
            $(this).append('hihi');
        }
      });
      return false;
    });
Run Code Online (Sandbox Code Playgroud)

为什么在ajax调用之后$(this)在这种情况下不起作用?如果我在ajax之前使用它但在之后没有效果它会工作.

Phi*_*ert 11

在jQuery ajax回调中,"this"是对ajax请求中使用的选项的引用.它不是对DOM元素的引用.

你需要首先捕获"外部" $(this):

$('.agree').live("click", function(){  // use live for binding of ajax results
      var id=($(this).attr('comment_id'));
      var $this = $(this);
      $.ajax({
        type: "POST",
        url: "includes/ajax.php?request=agree&id="+id,
        success: function(response) {
                $this.append('hihi');
        }
      });
      return false;
    });
Run Code Online (Sandbox Code Playgroud)