<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>冒泡和阻止冒泡</title> <script src="jquery.js"></script> </head> <body> <div id="out"> <div id="middle"> <a href="#">测试</a> </div> </div> <script> $("#out").on("click",function(){console.log("out");}); $("#middle").on("click",function(){console.log("middle");}); $("a").on("click",function(event){ console.log("a"); //event.stopPropagation(); //阻止冒泡,但不阻止a标签的默认行为 //return false; //阻止a标签跳转的默认行为 //event.preventDefault(); //只阻止默认行为,不阻止冒泡 //event.stopImmediatePropagation(); //阻止所有事件,包括平级的 }); $("a").on("click",function(event){ console.log("b"); }); </script> </body> </html>
结果: a b middle out
为了阻止事件冒泡,提供了四种方法:
event.stopPropagation(); //阻止冒泡,但不阻止a标签的默认行为 return false; //阻止a标签跳转的默认行为 event.preventDefault(); //只阻止默认行为,不阻止冒泡 event.stopImmediatePropagation(); //阻止所有事件,包括平级的
默认行为:当点击链接的时候,网址后面不会自动添加以#开头的字符