3

我想知道为什么 $(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;
    });

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

4

1 回答 1

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;
    });
于 2009-09-08T08:52:32.763 回答