如果我们在 elementFoo
上观察,在纯 JavaScript 中是真的吗:
elementFoo.addEventListener("click", function(ev) {
console.log(ev.currentTarget, this);
});
那么 ev.currentTarget
和 this
将永远是 elementFoo
?
这有点难记,因为在 jQuery 中,如果我们委托(delegate)事件:
$("#table-foo").on("click", "tr", function(ev) {
console.log(ev.currentTarget, this);
});
然后 ev.currentTarget
和 this
都将成为 tr
元素。是不是使用addEventListener()
,就不能有这种行为了? (唯一的方法是让 ev.target
成为 td
元素,而不是 tr
?
最佳答案
Is it true that in plain JavaScript, if we observe on elementFoo:...then ev.currentTarget and this will always be elementFoo?
是的。你可以阅读它here :
It always refers to the element the event handler has been attached to as opposed to event.target which identifies the element on which the event occurred.
我没有看到矛盾:
例如,如果您有 this :
然后你点击 span
: 然后 :
$( "body" ).on( "click", "p", function(e) {
console.log( "delegateTarget" , e.delegateTarget.nodeName ) //BODY
console.log( "currentTarget" ,e.currentTarget.nodeName) //P
console.log( "target" , e.target.nodeName) //SPAN
console.log( "this" , $(this)[0].nodeName) //P - the middle atached element
});
将产生:
delegateTarget BODY
currentTarget P
target SPAN
this P
关于javascript - addEventListener() 是否总是将 ev.currentTarget 和 "this"作为我们观察到的元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34973493/