阻止冒泡
w3c的方法是event.stopPropagation(),IE則是使用event.cancelBubble = true;
兼容寫法
<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標籤點擊事件的默認行為都無法執行,也就是都無法跳轉。
兼容寫法
<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>
return false
javascript的return false只會阻止默認行為,且只能在dom0事件中生效。
而用jQuery的話則既阻止默認行為又防止對象冒泡。
<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;
});