1. 程式人生 > >js中的preventDefault和stopPropagation_阻止事件

js中的preventDefault和stopPropagation_阻止事件

首先講解一下js中preventDefault和stopPropagation兩個方法的區別:

     preventDefault方法的起什麼作用呢?我們知道比如<a href="http://www.baidu.com">百度</a>,這是html中最基礎的東西,起的作用就是點選百度連結到http://www.baidu.com,這是屬於<a>標籤的預設行為,而preventDefault方法就是可以阻止它的預設行為的發生而發生其他的事情。看一段程式碼大家就明白了:

     <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "

http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>JS阻止連結跳轉</title>
<script type="text/javascript"> 
function stopDefault( e ) { 
     if ( e && e.preventDefault ) 
        e.preventDefault(); 
    else 
        window.event.returnValue = false; 
        
    return false; 

</script> 
</head>
<body>
<a href="
http://www.baidu.com
" id="testLink">百度</a> 
<script type="text/javascript"> 
var test = document.getElementById('testLink'); 
test.onclick = function(e) { 
   alert('我的連結地址是:' + this.href + ', 但是我不會跳轉。'); 
   stopDefault(e); 

</script>
</body>
</html>

此時點選百度連結,不會開啟http://www.baidu.com

,而只是彈出一個alert對話方塊。

     preventDefault方法講解到這裡,stopPropagation方法呢?講stopPropagation方法之前必需先給大家講解一下js的事件代理。

      事件代理用到了兩個在JavaSciprt事件中常被忽略的特性:事件冒泡以及目標元素。當一個元素上的事件被觸發的時候,比如說滑鼠點選了一個按鈕,同樣的事件將會在那個元素的所有祖先元素中被觸發。這一過程被稱為事件冒泡;這個事件從原始元素開始一直冒泡到DOM樹的最上層。對任何一個事件來說,其目標元素都是原始元素,在我們的這個例子中也就是按鈕。目標元素它在我們的事件物件中以屬性的形式出現。使用事件代理的話我們可以把事件處理器新增到一個元素上,等待事件從它的子級元素裡冒泡上來,並且可以很方便地判斷出這個事件是從哪個元素開始的。

     stopPropagation方法就是起到阻止js事件冒泡的作用,看一段程式碼。

     <!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xHTML1/DTD/xHTML1-transitional.dtd">
<HTML XMLns="http://www.w3.org/1999/xHTML" lang="gb2312">
<head>
<title> 阻止JS事件冒泡傳遞(cancelBubble 、stopPropagation)</title>
<meta name="keywords" content="JS,事件冒泡,cancelBubble,stopPropagation" />
<script>
function doSomething (obj,evt) {
alert(obj.id);
var e=(evt)?evt:window.event;
if (window.event) {
   e.cancelBubble=true;     // ie下阻止冒泡
} else {
   //e.preventDefault();
   e.stopPropagation();     // 其它瀏覽器下阻止冒泡
}
}
</script>
</head>
<body>
<div id="parent1" onclick="alert(this.id)" style="width:250px;background-color:yellow">
<p>This is parent1 div.</p>
<div id="child1" onclick="alert(this.id)" style="width:200px;background-color:orange">
   <p>This is child1.</p>
</div>
<p>This is parent1 div.</p>
</div>
<br />
<div id="parent2" onclick="alert(this.id)" style="width:250px;background-color:cyan;">
<p>This is parent2 div.</p>
<div id="child2" onclick="doSomething(this,event);" style="width:200px;background-color:lightblue;">
   <p>This is child2. Will bubble.</p>
</div>
<p>This is parent2 div.</p>
</div>
</body>
</HTML>

大家執行一下上面的程式碼就明白了。