我知道我可以抓住单个ID的元素。
无论如何,我可以将侦听器附加到父div 并传递单击的单个跨度的 ID?
<div id = "divId">
<span id="one"></span>
<span id="two"> </span>
</div>
.JS
document.getElementById("two").addEventListener("click", someFunction);
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>
如果用户单击的节点是用户要测试的元素的子级e.target
则该节点将是另一个节点。现在检查这一点的明智方法是在文档级别侦听并迭代路径(或使用一些委派库,其中有很多):
向文档添加一个事件侦听器:
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
}
});
亚当的答案是正确的,省去了不少麻烦。但是,有一种更好,最简单的方法来解决这个问题。请检查此答案
利用 Event.currentTarget,它像这样:
<ul>
<li class="list_item" data-mydata="hello there!">
<img src="..." alt="" width="50", height="50">
</li>
<li class="list_item" data-mydata="hello world">
<img src="..." alt="" width="50", height="50">
</li>
</ul>
<script>
const items = document.querySelectorAll(".list_item");
items.forEach(node => {
node.addEventListener("click", e => {
let myvalue = e.currentTarget.dataset.mydata;
console.log(myvalue); //hello there! || hello world It depends on which element the user has clicked
})
})
</script>
我希望这是有用的
由于我没有足够的学分来评论,因此添加新答案。
与@CubeInTheBox分享的答案不同,我认为利用相应元素的事件捕获/冒泡的概念可以更好地实现,而不是为每个目标元素添加事件侦听器。对于上面共享的示例,替代方案是:
<ul>
<li class="list_item" data-mydata="hello there!">
<img src="..." alt="" width="50", height="50">
</li>
<li class="list_item" data-mydata="hello world">
<img src="..." alt="" width="50", height="50">
</li>
</ul>
<script>
const parentElement = document.querySelector('ul');
parentElement.addEventListener('click', e => {
// If you want to add the listener on li alone and not on image
if (e.target.className === 'list_item') {
const myvalue = e.target.dataset.mydata;
console.log(myvalue);
}
});
</script>
请注意,e.currentTarget
不适用于这种情况,因为它将返回事件绑定到的父ul
。