简体   繁体   English

观察元素中具有单独点击观察功能的元素的点击

[英]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. 发生的事情是,当单击child1时,由于child1在父对象内,因此将触发父对象。 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. 除非您明确停止冒泡,否则给定元素上的事件会在DOM上冒泡,直到它们到达根节点为止。 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/ 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. 并将click事件传递到onclick函数中。

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. 我建议在父级上使用.unbind(),以防单击子级。 For example, 例如,

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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