冒泡事件就是点击子节点,会向上触发父节点,祖先节点的点击事件。
方法1:
event.stopPropagation(); // 阻止事件冒泡
有时候点击提交按钮会有一些默认事件。但是如果没有通过验证的话,就不应该继续。这时候可以通过设置event.preventDefault(); //阻止默认行为 ( 表单提交 )。
方法2:
return false;
示例代码:
<script type="text/javascript" src="/jquery/jquery.js"></script> <script type="text/javascript"> $(function(){ // 为span元素绑定click事件 $('span').bind("click",function(event){ var txt = $('#msg').html() + "<p>内层span元素被点击.<p/>"; $('#msg').html(txt); event.stopPropagation(); // 阻止事件冒泡 }); // 为div元素绑定click事件 $('#content').bind("click",function(event){ var txt = $('#msg').html() + "<p>外层div元素被点击.<p/>"; $('#msg').html(txt); event.stopPropagation(); // 阻止事件冒泡 }); }) </script>
<div id="content"><span>内层span元素</span></div> <div id="msg"></div>