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

时间:2022-10-08 08:29:04

I am wondering why $(this) does not work after a jQuery ajax call.

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

My code is like this.

我的代码是这样的。

$('.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;
    });

Why doesnt the $(this) work in this case after ajax call? It would work if I use it before the ajax but no effect after.

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

1 个解决方案

#1


11  

In a jQuery ajax callback, "this" is a reference to the options used in the ajax request. It's not a reference to a DOM element.

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

You need to capture the "outer" $(this) first:

你需要首先捕获“外部”$(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;
    });

#1


11  

In a jQuery ajax callback, "this" is a reference to the options used in the ajax request. It's not a reference to a DOM element.

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

You need to capture the "outer" $(this) first:

你需要首先捕获“外部”$(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;
    });