Jquery绑定将此返回到整个文档



如何制作:

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

像这样:

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

但仍然有效?

您可以使用提供给函数的事件参数,并且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);
});

最新更新