简体   繁体   English

如何将事件侦听器添加到按钮元素

[英]How can I add event listener to just button element

Here is my code.这是我的代码。

<button id ="id"><span>fire!</span></button>
<script>
document.getElementById('id').addEventListener('click',e=>{
    console.log(e.target)
}) 
</script>

then we can find simple button in DOM.然后我们可以在 DOM 中找到简单的按钮。 Once I click button, script returns单击按钮后,脚本将返回

<span>fire<\span> 

or或者

<button id="id"> ...</button>

. .

How can I add event listener to just button element?如何将事件侦听器添加到按钮元素?

This is as one of the options... You can use the currentTarget .这是选项之一...您可以使用currentTarget

In your case, it will be like this:在您的情况下,它将是这样的:

 document.getElementById('id').addEventListener('click', e=> { console.log(e.currentTarget); });
 <button id ="id"><span>fire!</span></button>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM