1.什么是冒泡
eg:
<!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="../../js/jQuery1.11.1.js"></script> <script type="text/javascript"> $(function () { //為span元素綁定click事件 $('span').bind('click', function () { var txt = $('#msg').html() + '<p>內層span元素被點擊</p>'; $('#msg').html(txt); }); //為span元素綁定click事件 $('#content').bind('click', function () { var txt = $('#msg').html() + '<p>外層div元素被點擊</p>'; $('#msg').html(txt); }); //為span元素綁定click事件 $('body').bind('click', function () { var txt = $('#msg').html() + '<p>body元素被點擊</p>'; $('#msg').html(txt); }); }); </script> </head> <body> <div id="content"> 外層div元素 <span>內層span元素</span> </div> <div id="msg"></div> </body> </html>
當你單擊‘內層span元素’時,即觸發<span>元素的click事件時,會輸出3條記錄
即:
內層span元素被點擊
外層div元素被點擊
body元素被點擊
這就是事件冒泡引起的。
2.事件冒泡引發的問題
01.事件對象
在程序中使用事件對象,只需要為函數添加一個參數,jQuery代碼如下:
$('element').bind('click',function(event){ //event:事件對象 });
02.停止事件冒泡
在jQuery中提供了stopPropagation()方法來停止事件冒泡
以span元素綁定click事件為例:
//為span元素綁定click事件 $('span').bind('click', function (event) { //event:事件對象 var txt = $('#msg').html() + '<p>內層span元素被點擊</p>'; $('#msg').html(txt); event.stopPropagation(); //停止事件冒泡 });
當你單擊‘內層span元素’時,即觸發<span>元素的click事件時,這時只會輸出1條記錄
即:
內層span元素被點擊
這樣就解決了冒泡問題
03.阻止默認行為
網頁中的元素有自己默認的行為,例如,單擊超鏈接后會跳轉,單擊‘提交’表單會提交,有時需要阻止元素的默認行為
在jQuery中,提供了preventDefault()方法來阻止元素的默認行為。
eg:以輸入提交為例
<!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="../../js/jQuery1.11.1.js"></script> <script type="text/javascript"> $(function () { $('#sub').bind('click', function (event) { var username = $('#username').val(); //獲取元素的值 if (username == "") { //判斷是否為空 alert('文本框的值不能為空'); //提示信息 event.preventDefault(); //阻止默認行為(表單提交) } }); }); </script> </head> <body> <form action="/"> 用戶名:<input type="text" id="username" /> <input type="submit" value="提交" id="sub" /> </form> </body> </html>
假如你不輸入內容,這樣就可以阻止默認行為(表單提交)
總結:如果想同時對事件停止冒泡和默認行為,可以在事件處理函數中返回false。這是對在事件對象上同時調用stopPropagation()方法和preventDefault()方法的一種簡寫方式。
在上面表單的例子中,可以把
event.preventDefault(); //阻止默認行為(表單提交)
改寫為:
return false;
也可以把事件冒泡中的
event.stopPropagation(); //停止事件冒泡
改寫為:
return false;
04.事件捕獲
05.事件對象的屬性
事件對象的屬性 詳情請參考:http://www.w3school.com.cn/jsref/dom_obj_event.asp