本文介绍了Javascript被“点击".元素addEventListener的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我知道我可以获取单个ID的元素.
I know I can grab the element of an individual ID.
是否可以将侦听器附加到父div并传递被单击的单个范围的ID?
Anyway I can attach a listener to the parent div and pass the ID of the individual span that was clicked?
<div id = "divId">
<span id="one"></span>
<span id="two"> </span>
</div>
JS
document.getElementById("two").addEventListener("click", someFunction);
推荐答案
您可以使用event
对象并访问其target
属性
You can use the event
object and access its target
property
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>
这篇关于Javascript被“点击".元素addEventListener的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!