【问题标题】:Jquery bind returns this to entire documentJquery 绑定将此返回到整个文档
【发布时间】:2021-02-15 13:00:09
【问题描述】:

制作方法:

$('.x').on('click', function() {
    console.log($(this).attr('id'));
});

这样:

$('.x').on('click', () => {
    console.log($(this).attr('id'));
});

但仍在工作?

【问题讨论】:

标签: jquery return click this bind


【解决方案1】:

您可以使用提供给函数的事件参数,event.target 将等于 this 在常规函数中调用。

$('.x').on('click', (event) => {
    console.log($(event.target).attr('id'));
});

您不能使用this 的原因如下所示。我之前提供的链接显示了将上下文绑定到箭头函数的复杂程度。 Jquery 为您的处理程序使用类似的方法

var customObject = {
  data: "test"
}

function test(func) {
  func.call(customObject);
}

test(function () 
{
  console.log(this);
});

test(() => {
  console.log(this);
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-10-21
    • 2020-12-05
    • 2014-01-29
    • 1970-01-01
    • 2021-10-03
    • 1970-01-01
    • 2020-03-08
    • 1970-01-01
    相关资源
    最近更新 更多