首页 > 解决方案 > 在 javascript onevent 函数中使用 this

问题描述

为什么我不能在 javascript 中使用“this”关键字访问当前元素?它适用于 jquery,但我想学习 vanilla javscript 等价物,但我似乎找不到答案。

      document.getElementById('icon').onclick = () => {
        this.style.display = 'none'
        console.log(this) // prints the window instead of element?
      }

标签: javascripthtml

解决方案


document.getElementById('icon').onclick = ( ) => { 
         event.currentTarget.style.display='none';               
      }
<div id='icon'>xxx</div>


推荐阅读