我正在尝试使用 JavaScript 来获取单击元素的信息。
这是jsFiddle。
下面是我的代码。
let div = document.querySelector('div')
div.addEventListener('click', function(event) {
// how to get the clicked p tag here?
// this?
// event.target.currentTarget?
})Run Code Online (Sandbox Code Playgroud)
<div>
<p>text 1</p>
<p>text 2</p>
</div>Run Code Online (Sandbox Code Playgroud)
我怎样才能this获取元素的信息?
答案: event.target
谢谢胡安·门德斯
e.target应该为您提供单击以生成事件的确切元素。
e.currentTarget将为您提供调用函数时事件所在的元素(从 冒泡后e.target)
div.addEventListener('click', (e) => {
console.log(e.target) // the p that was clicked
console.log(e.currentTarget) // this div
})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14631 次 |
| 最近记录: |