简体   繁体   中英

How to make event.path recognize elements inside an anchor tag?

To demonstrate my question, here's my version of HTML:

<body>
  <a href="google.com">
    <div>
      <h2>Hello</h2>
      <h4>Venus</h4>
    </div>
  </a>
</body>

Then I use 'onclick' for the body in Javascript:

document.body.onclick = function(event) {
  console.log(event.path)
}

When I click on the 'h2' tag, the console will log only [window, html, body, a] and not the elements inside of the 'a' tag.

The result I want is when I click the 'h2' tag, event.path will return an array of [window, html, body, a, div, h2]

This problem also exists with the 'p' tag.

Is there a way for the 'event.path' to includes elements inside 'a' tags? Thank you very much.

Maybe this will help you

 function handleClicks(e) { var path = []; var node = e.target; while(node != document) { !e.target.contains(node.parentNode) && path.push(node.nodeName); // if you want to exclude the elements inside the clicked element node = node.parentNode; } console.log(path); } document.body.addEventListener('click', handleClicks); 
 <body> <a href="#" id="not"> <div> <h2>Hello</h2> <h4>Venus</h4> </div> </a> </body> 

Edited

请避免在锚标记中使用“ div”,而可以将“ span”与某些需要的已定义用户类一起使用。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM