【问题标题】:Accessing $(this) inside of a $.post function? [duplicate]在 $.post 函数中访问 $(this)? [复制]
【发布时间】:2012-07-28 15:07:30
【问题描述】:

我在访问帖子中的函数内部的 $(this) 时遇到了很多麻烦 我要做的就是根据响应删除对象类。

  $.post("url.php?"+theData, {}, function(response){  etc.....

使用静态 #ID 可以正常工作,但我更愿意操纵 $this

【问题讨论】:

  • 如果您正在执行类似$('element').click(function(){ $.post(){ 的操作,您需要在帖子之前存储对 $(this) 的引用,以便您可以在函数中引用它,例如 $('element').cilck(function(){ var me = $(this); $.post("url.php?"+theData, {}, function(resposne({ //me is now $(this); }); });
  • 这可能只是范围问题,但发布更多代码,也许可以使用变量代替,但您的代码示例现在什么都没有显示?

标签: javascript jquery html ajax this


【解决方案1】:

试试

var self = this; 
$.post("url.php?"+theData, {}, function(response){
    $(self).show(); // manipulate this
});

【讨论】:

    【解决方案2】:

    这是来自异步事件的回调,因此指向该元素的this 丢失。

    您需要保留对外部 this(元素)的引用。一种方法是通过一个立即执行的函数来绑定它:

    $('#something').on('click', function() {
        $.post('somewhere.php').done((function(el) { return function(response) {
            $(el).removeClass('someClass');
        }; })(this));
    });
    

    【讨论】:

      【解决方案3】:

      变量this 始终指向当前上下文对象。

      var obj = { // declare object
        a: 2,
      
        b: function (p) { 
          alert(this.a + p); // here 'this' will point to obj if it was run by 'obj.b();' 
        }
      };
      
      obj.b(2); // call it's method
      

      你也可以设置当前的'this':

      var s = { a: 3 };
      
      var obj = {
        a: 2,
      
        b: function (p) { 
          alert(this.a + p); // here 'this' will be s 
        }
      };
      
      obj.b.call(s, 2);
      

      如果您在另一个 (f2) 中使用例如 2 个函数 (f1) 并且 f1 的上下文应该在 f2 中可用,那么最简单的方法是将其存储在变量中;

      $(buttonSelector).click(function () {
        var button = $(this);
      
        $.post(url, function (data) {
          //here button is available
        };
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-03-14
        • 2014-11-07
        • 2016-03-16
        • 1970-01-01
        • 2019-06-09
        • 2016-07-20
        • 1970-01-01
        • 2014-11-08
        相关资源
        最近更新 更多