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>內(nèi)層span元素被點(diǎn)擊</p>'; $('#msg').html(txt); }); //為span元素綁定click事件 $('#content').bind('click', function () { var txt = $('#msg').html() + '<p>外層div元素被點(diǎn)擊</p>'; $('#msg').html(txt); }); //為span元素綁定click事件 $('body').bind('click', function () { var txt = $('#msg').html() + '<p>body元素被點(diǎn)擊</p>'; $('#msg').html(txt); }); }); </script></head><body> <div id="content"> 外層div元素 <span>內(nèi)層span元素</span> </div> <div id="msg"></div></body></html>當(dāng)你單擊‘內(nèi)層span元素'時(shí),即觸發(fā)<span>元素的click事件時(shí),會(huì)輸出3條記錄
即:
內(nèi)層span元素被點(diǎn)擊
外層div元素被點(diǎn)擊
body元素被點(diǎn)擊
這就是事件冒泡引起的。

2.事件冒泡引發(fā)的問(wèn)題
01.事件對(duì)象
在程序中使用事件對(duì)象,只需要為函數(shù)添加一個(gè)參數(shù),jQuery代碼如下:
$('element').bind('click',function(event){ //event:事件對(duì)象});02.停止事件冒泡
在jQuery中提供了stopPropagation()方法來(lái)停止事件冒泡
以span元素綁定click事件為例:
//為span元素綁定click事件 $('span').bind('click', function (event) { //event:事件對(duì)象 var txt = $('#msg').html() + '<p>內(nèi)層span元素被點(diǎn)擊</p>'; $('#msg').html(txt); event.stopPropagation(); //停止事件冒泡 });當(dāng)你單擊‘內(nèi)層span元素'時(shí),即觸發(fā)<span>元素的click事件時(shí),這時(shí)只會(huì)輸出1條記錄
即:
內(nèi)層span元素被點(diǎn)擊
這樣就解決了冒泡問(wèn)題
03.阻止默認(rèn)行為
網(wǎng)頁(yè)中的元素有自己默認(rèn)的行為,例如,單擊超鏈接后會(huì)跳轉(zhuǎn),單擊‘提交'表單會(huì)提交,有時(shí)需要阻止元素的默認(rèn)行為
在jQuery中,提供了preventDefault()方法來(lái)阻止元素的默認(rèn)行為。
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(); //阻止默認(rèn)行為(表單提交) } }); }); </script></head><body> <form action="/"> 用戶名:<input type="text" id="username" /> <input type="submit" value="提交" id="sub" /> </form> </body></html>假如你不輸入內(nèi)容,這樣就可以阻止默認(rèn)行為(表單提交)
總結(jié):如果想同時(shí)對(duì)事件停止冒泡和默認(rèn)行為,可以在事件處理函數(shù)中返回false。這是對(duì)在事件對(duì)象上同時(shí)調(diào)用stopPropagation()方法和preventDefault()方法的一種簡(jiǎn)寫(xiě)方式。
在上面表單的例子中,可以把
event.preventDefault(); //阻止默認(rèn)行為(表單提交)
改寫(xiě)為:return false;
也可以把事件冒泡中的event.stopPropagation(); //停止事件冒泡
改寫(xiě)為:return false;
04.事件捕獲

05.事件對(duì)象的屬性

事件對(duì)象的屬性 詳情請(qǐng)參考:http://www.w3school.com.cn/jsref/dom_obj_event.asp
以上這篇深入理解jQuery中的事件冒泡就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持武林網(wǎng)。
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注