js中的preventDefault与stopPropagation详解
1.?preventDefault:?
比如<a href="http://www.baidu.com">百度</a>,這是html中最基礎(chǔ)的東西,起的作用就是點(diǎn)擊百度鏈接到http://www.baidu.com,這是屬于<a>標(biāo)簽的默認(rèn)行為;preventDefault方法就是可以阻止它的默認(rèn)行為的發(fā)生而發(fā)生其他的事情;
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 5 <title>JS阻止鏈接跳轉(zhuǎn)</title> 6 <script type="text/javascript"> 7 function stopDefault( e ) { 8 if ( e && e.preventDefault ) 9 e.preventDefault(); 10 else 11 window.event.returnValue = false; 12 13 return false; 14 } 15 </script> 16 </head> 17 <body> 18 <a href="http://www.baidu.com" id="testLink">百度</a> 19 <script type="text/javascript"> 20 var test = document.getElementById('testLink'); 21 test.onclick = function(e) { 22 alert('我的鏈接地址是:' + this.href + ', 但是我不會(huì)跳轉(zhuǎn)。'); 23 stopDefault(e); 24 } 25 </script> 26 </body> 27 </html>
此時(shí)點(diǎn)擊百度鏈接,不會(huì)打開http://www.baidu.com,而只是彈出一個(gè)alert對(duì)話框
2.?stopPropagation :
起到阻止js事件冒泡的作用;
2.1 講stopPropagation方法之前必需先給大家講解一下js的事件代理:?
(1) 事件代理用到了兩個(gè)在JavaSciprt事件中常被忽略的特性:事件冒泡以及目標(biāo)元素
事件冒泡: 當(dāng)一個(gè)元素上的事件被觸發(fā)的時(shí)候,比如說鼠標(biāo)點(diǎn)擊了一個(gè)按鈕,同樣的事件將會(huì)在那個(gè)元素的所有祖先元素中被觸發(fā)。這一過程被稱為事件冒泡;這個(gè)事件從原始元素開始一直冒泡到DOM樹的最上層.
目標(biāo)元素:?對(duì)任何一個(gè)事件來說,其目標(biāo)元素都是原始元素,在我們的這個(gè)例子中也就是按鈕。目標(biāo)元素它在我們的事件對(duì)象中以屬性的形式出現(xiàn)。使用事件代理的話我們可以把事件處理器添加到一個(gè)元素上,等待事件從它的子級(jí)元素里冒泡上來,并且可以很方便地判斷出這個(gè)事件是從哪個(gè)元素開始的。
下面看一段代碼:
<!DOCTYPE html> <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>
?
參考:http://www.jb51.net/article/46379.htm
?
轉(zhuǎn)載于:https://www.cnblogs.com/max-tlp/p/8257688.html
總結(jié)
以上是生活随笔為你收集整理的js中的preventDefault与stopPropagation详解的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 《长相思·九月西风兴》第八句是什么
- 下一篇: MYSQL explain详解[转载]