简体   繁体   中英

jquery - checking if element is clicking and sub-elements aren't clicked

I have this html code:

<div id="area">Click me <span id="forbidden">Hi Guys</span></div>

I would like to do check if only #area clicked, but not the area of forbidden, eventhough it is inside the div "area".

Thanks in advance, Daniel.

The .target property of the event object will give you the DOM element that initiated the event:

$("#area").click(function(e) {
   if (e.target.id != "forbidden") {
       // do something
   }
});

Another approach would be to use the stopPropagation on the forbidden element.

$('#area').click(function(){
  // not forbidden
});


$('#forbidden').click(function(e){
    e.stopPropagation();
});

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