简体   繁体   中英

Observing click of element within element that has a separate click observe function

I have an element within another element and both have separate click functions. What I would like to do is ignore or stop the parent element if the child element has a click function. For example:

<div class="parent">
   <div class="child1">Child Click Function</div>
   Parent Click Function
</div>
<script type="text/javascript">
document.observe('dom:loaded',function(){
   if ($$('.parent') != undefined) {
      $$('.parent').invoke('observe','click', function(e) {    
         alert('parent');         
      });
   }
   if ($$('.child1') != undefined) {
      $$('.child1').invoke('observe','click', function(e) {    
         alert('child');         
      });
   }        
});
</script>

What happens is that when child1 is clicked, both that and parent are triggered since child1 is within parent. I would like disable/stop the observe when child is selected, but when you click on anything else inside parent, it works as it should.

Thanks.

You're encountering what's known as "event bubbling". Events on a given element bubble up the DOM until they reach the root node unless you explicitly stop the bubbling. Since it looks like you're using Prototype, updating your child's event handler to the following should do the trick:

$$('.child1').invoke('observe','click', function(e) {    
    Event.stop(e);    
    alert('child');         
});

http://api.prototypejs.org/dom/Event/prototype/stop/

I'm not sure which one works, but I usually use both:

if (event.cancelBubble)
    event.cancelBubble();
if (event.stopImmediatePropagation)
    event.stopImmediatePropagation();

And pass the click event into the onclick function.

Both stop propagation and cancel bubble will stop the propagation of the event all together , from what I get is you want to bypass the event associated with the parent. I would suggest to use .unbind() on the parent in case the child is clicked. For example,

 (CHECK CHILD CLICK) { 
 $('.parent').unbind('click');}

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