【问题标题】:Referring to the triggering object in the done() block of a post() call?引用 post() 调用的 done() 块中的触发对象?
【发布时间】:2017-11-14 14:11:18
【问题描述】:

我有一个post() 调用绑定到一组图像的click() 方法。

post() 调用中,我可以引用jQuery(this) 并通过它访问原始对象。 (例如数据参数,或更改其状态):

jQuery('.vote .magic_button').click(function() {
  jQuery.post(url, {
      action: 'ajax_vote',
      'vote_target': jQuery(this).data('postid')
    })
    .done(function(data) {
      // $img = jQuery(this).find('img');         
    })
});

当 AJAX 调用返回时,在验证响应后,我想引用最初单击的图像,但在这个新上下文中不再是 this

如何在不必将信息传回 data 参数内的情况下访问它?

【问题讨论】:

    标签: javascript jquery ajax


    【解决方案1】:

    您可以使用var that = this 解决方法或仅使用ES5 .bind 函数来正确设置this

    jQuery('.vote .magic_button').click(function() {
      jQuery.post(url, {
          action: 'ajax_vote',
          'vote_target': jQuery(this).data('postid')
        })
        .done(function(data) {
          // $img = jQuery(this).find('img');         
        }.bind(this))
    });
    

    Documentation

    【讨论】:

    • 这似乎比“自我”分配技巧更优雅。但是bind 有额外的要求吗?它适用于常规 JS,还是我需要预处理器?
    • 没什么,只是一个相对较新的浏览器。请参阅链接文档中的兼容性表。
    • Mmmmh.... 在 FF Dev 我得到一个非常好的jQuery.post(...).done(...).bind is not a function...
    • @artgb 不,它在该函数中使用时设置this 值。
    • @artgb 对不起,我打错了。 bind 调用应该附加到 done 函数。已修复 另请参阅更新的小提琴 jsfiddle.net/v20j8jet/2
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多