为什么我不能使用javascript中的'this'关键字访问当前元素?它可以在jquery中工作,但是我想学习与javscript等效的东西,而我似乎找不到答案。
document.getElementById('icon').onclick = () => {
this.style.display = 'none'
console.log(this) // prints the window instead of element?
}
答案 0 :(得分:2)
document.getElementById('icon').onclick = ( ) => {
event.currentTarget.style.display='none';
}
<div id='icon'>xxx</div>
答案 1 :(得分:0)
这与使用箭头功能时的功能范围有关。
来自MDN:
箭头函数表达式在语法上是常规函数表达式的紧凑选择,尽管没有自身绑定到 this , arguments , super 或 new.target 关键字。箭头函数表达式不适合用作方法,不能用作构造函数。
如果您想使用this
,请使用function(){...}
而不是()=>{...}
document.getElementById('icon').onclick = function(){
this.style.display = 'none'
console.log(this) // prints the window instead of element?
}