什么是事件冒泡?
事件冒泡就是當父元素和子元素存在同一事件時在子元素的事件處理程序中會自動調用其父級元素的事件處理程序。
demo:
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title>事件冒泡</title> <script src="jquery-1.8.3.min.js"></script> <script> $(function () { $("#div").click(function () { $(this).text("我是div"); }); $("#img").click(function () { $(this).parent().css("border", "1px solid red"); }); }) </script> </head> <body> <div id="div"> <img id="img" src="images/gd.jpg" /> </div> </body> </html>
當點擊div下的img元素時界面效果如圖:
通過上面代碼我們只是想當鼠標點擊圖片時讓div的邊框成紅色並沒有要刪除圖片,但他在執行子元素(img)的事件處理程序時自動調用了父級元素(div)這就是事件冒泡。
如何取消事件冒泡?
事件冒泡是可以由程序員手工取消的也就是在子元素的事件處理程序中手動的停止調用父級元素
demo:
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title>事件冒泡</title> <script src="jquery-1.8.3.min.js"></script> <script> $(function () { $("#div").click(function () { $(this).text("我是div"); }); $("#img").click(function () { $(this).parent().css("border", "1px solid red"); event.stopPropagation();}); }) </script> </head> <body> <div id="div"> <img id="img" src="images/gd.jpg" /> </div> </body> </html>
如上所示代碼就可以取消事件冒泡
demo:
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title>事件冒泡</title> <script src="jquery-1.8.3.min.js"></script> <script> $(function () { $("#div").click(function () { if( event.target == event.currentTarget){ $(this).text("我是div"); } }); $("#img").click(function () { if( event.target == event.currentTarget){ $(this).parent().css("border", "1px solid red"); } }); }) </script> </head> <body> <div id="div"> <img id="img" src="images/gd.jpg" /> </div> </body> </html>

