javascript - 在 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?
}
解决方案
document.getElementById('icon').onclick = ( ) => {
event.currentTarget.style.display='none';
}
<div id='icon'>xxx</div>
推荐阅读
- php - Symfony 4 实现 REST API
- java - 我将如何创建一个将数组添加到数组列表并在其上调用方法的主要方法?
- azure-sql-database - 进行 azure sql 备份时出错
- oracle - PL/SQL 函数返回自定义类型异常
- mongodb - MongoDb 中的多个 $and $or 查找
- python - 使用 OneHotEncoder inverse_transform
- ruby-on-rails - 如何通过设置键元素的优先级来使用字符串键对 ruby 哈希进行排序?
- python - 在 Django 中使用 clean() 方法
- android - Android 翻滚自定义 TextViews onResume
- java - WebDriver 在无头模式下保存问题