如何制作:
$('.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);
});