如果嵌套元素触发事件,则不要让容器处理它

我有一个包含另一个div的div。 如果用户单击内部div,我只希望执行附加到此元素的eventhandler。 现在首先执行内部元素的事件处理程序,然后执行外部元素的事件处理程序。 有没有办法改变这个?

   Demo     $(document).ready(function(){ $("#containerElement").click(function(event){ alert("This comes from container"); }); $("#innerElement").click(function(event){ alert("This comes from inner element"); }); });  
This is the container
This is the inner element

你可以停止传播 :

 $("#innerElement").click(function(event){ alert("This comes from inner element"); event.stopPropagation(); }); 

添加event.stopPropagation();

 $("#innerElement").click(function(event){ alert("This comes from inner element"); event.stopPropagation(); }); 

从处理程序返回false将阻止冒泡(除其他外):

 $("#innerElement").click(function(event){ alert("This comes from container"); return false; }); 

event.stopPropagation()添加到innerElement事件处理程序。 有关更多信息,请参阅jQuery文档 。

 $("#innerElement").click(function(event){ alert("This comes from inner element"); event.stopPropagation(); });