夺命雷公狗jquery---26事件冒泡介绍和阻止方法
什么是事件冒泡可以通过以下代码即可知晓
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> <style type="text/css"> #div1{ width:400px; height:400px; background-color:red; } #div2{ width:300px; height:300px; background-color:blue; } #div3{ width:200px; height:200px; background-color:green; } </style> <script src="js/jquery.js"></script> <script> $(function(){ $('#div1').bind('click',function(){ alert('div1'); }); $('#div2').bind('click',function(){ alert('div2'); }); $('#div3').bind('click',function(){ alert('div3'); }); }) </script> </head> <body> <div id="div1"> <div id="div2"> <div id="div3"></div> </div> </div> </body> </html>
阻止的方法其实也很简单,只要加上event 和event.stopPropagetion()即可阻止事件冒泡了,如下代码所示
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> <style type="text/css"> #div1{ width:400px; height:400px; background-color:red; } #div2{ width:300px; height:300px; background-color:blue; } #div3{ width:200px; height:200px; background-color:green; } </style> <script src="js/jquery.js"></script> <script> $(function(){ $('#div1').bind('click',function(){ alert('div1'); }); $('#div2').bind('click',function(event){ alert('div2'); event.stopPropagation(); }); $('#div3').bind('click',function(event){ alert('div3'); event.stopPropagation(); }); }) </script> </head> <body> <div id="div1"> <div id="div2"> <div id="div3"></div> </div> </div> </body> </html>