js事件冒泡

javaSciprt事件中有兩個很重要的特性:事件冒泡以及目標元素。javascript


事件冒泡: 當一個元素上的事件被觸發的時候,好比說鼠標點擊了一個按鈕,一樣的事件將會在那個元素的全部祖先元素中被觸發。這一過程被稱爲事件冒泡;這個事件從原始元素開始一直冒泡到DOM樹的最上層。html


目標元素: 任何一個事件的目標元素都是最開始的那個元素,在咱們的這個例子中也就是label。使用事件代理的話咱們能夠把事件處理器添加到一個元素上,等待一個事件從它的子級元素裏冒泡上來,而且能夠很方便地得知這個事件是從哪一個元素開始的。java

事件的冒泡和捕獲
捕獲是從上級元素到下級元素,冒泡是從下級元素到上級元素。瀏覽器

如下程序模擬一下事件冒泡:函數

<%@ 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查看控制檯輸出:ui

 

能夠看到點擊label後事件觸發的順序:代理

1.觸發label的onclick事件;htm

2.觸發input的onclick事件;對象

3.input的點擊事件引發事件冒泡觸發外層的label點擊事件。blog

解決辦法:

若是點擊了某個元素不想讓事件繼續傳播能夠使用如下方式

<%@ 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的點擊事件,而且只調用一次。