阻止冒泡
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;
});
发表回复