w3c的方法是event.stopPropagation(),IE則是使用event.cancelBubble = true;javascript
<div class="parent"> <div class="child"></div> </div> <script> const child = document.querySelector(".child"); child .addEventListener("click",function(event){ event = window.event || event if(event.stopPropagation){ event.stopPropagation() }else{ event.cancelBubble = true } }) </script>
w3c的方法是event.preventDefault(),IE則是使用event.returnValue = false;
若是事件是能夠冒泡的,在冒泡過程當中也能夠阻止默認行爲,舉個例子,咱們在body標籤的click事件中阻止默認行爲,那麼頁面上全部的a標籤點擊事件的默認行爲都沒法執行,也就是都沒法跳轉。java
<input id="div" value="123"> <script> const div = document.getElementById("div") div.addEventListener("copy",function(event){ event = window.event || event; if(event.preventDefault){ event.preventDefault() }else{ event.returnValue = false; } }) </script>
javascript的return false只會阻止默認行爲,且只能在dom0事件中生效。
而用jQuery的話則既阻止默認行爲又防止對象冒泡。dom
<a href="www.baidu.com" id="a"></a> const a = document.getElementById("a") a.onclick = function(){ return false; };
<a href="www.baidu.com" id="a"></a> $("#a").on('click',function(){ return false; });