javascript Javascript获取“点击”元素addEventListener

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30786154/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 12:41:34  来源:igfitidea点击:

Javascript get "clicked" element addEventListener

javascript

提问by Doc Holiday

I know I can grab the element of an individual ID.

我知道我可以获取个人 ID 的元素。

Anyway I can attach a listener to the parent div and pass the ID of the individual span that was clicked?

无论如何,我可以将侦听器附加到父 div 并传递单击的单个跨度的 ID?

<div id = "divId">
  <span id="one"></span>
  <span id="two"> </span>
 </div>

JS

JS

document.getElementById("two").addEventListener("click", someFunction);

回答by AmmarCSE

You can use the eventobject and access its targetproperty

您可以使用该event对象并访问其target属性

document.getElementById("divId").addEventListener("click", someFunction);

function someFunction(event) {
  console.log(event.target.id);
}
<div id="divId">
  <span id="one">one</span>
  <span id="two"> two</span>
</div>

回答by Adam

If the user clicked on a node that was a child of the element the user wanted to test e.targetwill be a different node. The sensible way to check this nowadays is to listen at the document level and iterate the path (or use some delegation library, of which there are many):

如果用户单击作为用户想要测试的元素的子元素的节点,则该节点e.target将是不同的节点。现在检查这一点的明智方法是在文档级别进行侦听并迭代路径(或使用一些委托库,其中有很多):

Add one event listener to the document:

向文档添加一个事件侦听器:

const isOnId = (path,id) => path.some(element => element.id === id);

document.addEventListener('click',function(e) {
  if(isOnId(e.path,'two')) {
    //you clicked on or in element with an id two
  } else {
    //you clicked on something else
  }
});