简体   繁体   中英

How can I detect whether bubbling encounters a certain type of element?

I have several div elements with a canvas in each of them:

I decided to add a listener to the div with ID everything. How can I detect whether a click on that div is also a click on a div with class dog?

I tried

document.getElementById('everything').addEventListener('click', function(e) {
  console.debug(e.target);
});

but console.debug(e.target); only gives me the canvas that was clicked on.

I could just simply assign an event listener to the dog div, but I don't want to do that since I might have lots of children divs inside of the div IDed with 'everything'.

I'm sorry this is jQuery But try this.

and It's hardly possible to make sure if #everything is a parent of .dog or not though

The case "#everything" is parent of ".dog", this should work.

$("#everything").on("click",function(e){
  if $(this).closest(".dog").length > 0
    console.log("element covering both #everything and .dog has clicked")
  else
    console.log("#everything has clicked but not .dog")
})

hope This would help.

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