js事件冒泡,js冒泡
javaSciprt事件中有兩個很重要的特性:事件冒泡以及目標元素。
事件冒泡: 當一個元素上的事件被觸發的時候,比如說滑鼠點擊了一個按鈕,同樣的事件將會在那個元素的所有祖先元素中被觸發。這一過程被稱為事件冒泡;這個事件從原始元素開始一直冒泡到DOM樹的最上層。
目標元素: 任何一個事件的目標元素都是最開始的那個元素,在我們的這個例子中也就是label。使用事件代理的話我們可以把事件處理器添加到一個元素上,等待一個事件從它的子級元素裡冒泡上來,並且可以很方便地得知這個事件是從哪個元素開始的。
事件的冒泡和捕獲
捕獲是從上階項目到下級元素,冒泡是從下級元素到上階項目。
以下程式類比一下事件冒泡:
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html> <head> <base href="<%=basePath%>"> <title>index</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <script type="text/javascript"> function fun1(){ console.log("fun1 call!!"); } function fun2(event){ console.log("fun2 call!!"); } </script> </head> <body> <label onclick="fun2(event)"> radio : <input type="radio" onclick="fun1()"/> </label> </body></html>
訪問該頁面點擊label查看控制台輸出:
可以看到點擊label後事件觸發的順序:
1.觸發label的onclick事件;
2.觸發input的onclick事件;
3.input的點擊事件引起事件冒泡觸發外層的label點擊事件。
解決辦法:
如果點擊了某個元素不想讓事件繼續傳播可以使用以下方式
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html> <head> <base href="<%=basePath%>"> <title>index</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <script type="text/javascript"> function fun1(){ console.log("fun1 call!!"); } function fun2(event){ console.log("fun2 call!!"); stopDefault(event); } function stopDefault(e) { //如果提供了事件對象,則這是一個非IE瀏覽器 if(e && e.preventDefault) { //阻止預設瀏覽器動作(W3C) e.preventDefault(); } else { //IE中阻止函數器預設動作的方式 window.event.returnValue = false; } return false; } </script> </head> <body> <label onclick="fun2(event)"> radio : <input type="radio" onclick="fun1()"/> </label> </body></html>這樣只會調用label的點擊事件,並且只調用一次。