控制上下文在jQuery按钮代理功能



我需要隔离在jQuery中单击按钮时附加的值。但是,我还需要在$.proxy(...)中包装单击处理程序,以便为后续函数调用维护上下文:

$('#' + tab.buttonId).click($.proxy(function() {
   this.pop($(this).val());
}, this));
  • 。pop需要应用到对象
  • $(this).val()需要来自按钮

我如何使每个调用this引用正确的东西?

你可以使用e.target,它将指向按钮对象:

$('#' + tab.buttonId).click($.proxy(function(e) {
   this.pop($(e.target).val());
}, this));

我认为你传递的this应该在代理函数参数中:

$('#' + tab.buttonId).click($.proxy(function() {
   this.pop($(this).val());
}, this));

我会将上下文存储在一个变量中:

// the context
var that = this;
$('#' + tab.buttonId).click(function() {
   that.pop($(this).val());
});

这是常见的做法,未来的读者不了解$.proxy

也能理解它。

为您所单击的对象使用事件对象。e.target

function pop(val) {
  alert(val.text())
}
$('a').click($.proxy(function(e) {
  this.pop($(e.target));
}, this));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<a href="#">Click Me</a>

其他选项:使用Function.prototype.bind

$('a').click(function(e) {
     this.pop($(e.target));
}.bind(this));

或es6箭头函数,它们将保留词法this

$('a').click(e => {
    this.pop($(e.target));
});

最新更新