当用户单击锚点的子级时返回

问题描述 投票:0回答:1

如果用户单击锚点的子级,我想返回以下函数:

<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);

我怎样才能做这样的事?

javascript html reactjs dom next.js
1个回答
0
投票

实现目标的最简单方法是将事件侦听器直接添加到第一个

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>

© www.soinside.com 2019 - 2024. All rights reserved.