如果用户单击锚点的子级,我想返回以下函数:
<a href="/product/product-id">
I am a product
<div>
Add to favorites
</div>
</a>
const handleClick = (event) =>{
console.log(event);
// true -> if i click any of its children aka. the add to favorites
if(true){
event.preventDefault();
return;
}
// Route is about to change
NProgress.start();
}
document.addEventListener('click', handleClick);
我怎样才能做这样的事?
实现目标的最简单方法是将事件侦听器直接添加到第一个
div
元素内的 a
:
document.querySelector("a>div").addEventListener("click",ev=>{
ev.preventDefault();
console.log('take action on "Add to favorites"');
});
<a href="/product/product-id">
I am a product
<div>
Add to favorites
</div>
</a>