【问题标题】:Jquery AJAX call: $(this) does not work after successJquery AJAX 调用:$(this) 成功后不起作用
【发布时间】:2009-09-08 08:49:50
【问题描述】:

我想知道为什么在 jQuery ajax 调用之后 $(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;
    });

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

【问题讨论】:

标签: jquery ajax this


【解决方案1】:

在 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;
    });

【讨论】:

  • 还有一件事。我可以遍历它吗?最接近的? $this.closest('div').html('hihi');
  • 是的,您的新 $this 变量包含一个 jquery 对象,因此您可以像对待 $(this) 一样对待它
  • 好东西,对我也有帮助
猜你喜欢
  • 2014-08-02
  • 2011-09-17
  • 1970-01-01
  • 2014-01-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-08
  • 1970-01-01
相关资源
最近更新 更多