$(this)如何不能成为在jQuery单击处理程序中触发事件的元素? [英] how can $(this) not be the element that triggered the event in a jquery click handler?
问题描述
我有一个简单的点击处理程序
I have a simple click handler
<h1 id="test">
$('#test').click( ev => {
var $test = $(this);
console.log($test.text());
})
,但不起作用,$(this)
不是发射器元素.如果我检查this
,我会看到一个窗口"(?)(??)(??!)
but it does not work, $(this)
is not the emitter element. If I inspect this
I see a "window" (?) (??) (??!)
此外,如果我将代码更改为
also, if I change my code to
var $test = $(ev.toElement);
它完美地工作.
怎么可能?我的代码中有什么阻止jquery正确传递this
中的元素?
how can this be? what is in my code that prevents jquery to correctly pass the element in this
?
推荐答案
Arrow functions do not bind this
, arguments
etc. MDN.
箭头函数表达式的语法比函数短 表达式并按词法绑定
this
值(不绑定其自身的this
,arguments
,super
或new.target
).
An arrow function expression has a shorter syntax compared to function expressions and lexically binds the
this
value (does not bind its ownthis
,arguments
,super
, ornew.target
).
这篇关于$(this)如何不能成为在jQuery单击处理程序中触发事件的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!