event.stopPropagation()、event.preventDefault()与return false的区别

时间:2023-03-09 16:52:01
event.stopPropagation()、event.preventDefault()与return false的区别

做小demo时经常用到return false来取消默认事件,但一直不是很懂它和preventDefault()等的区别,今天查了查文档和大神们的博客,在这里对相关知识点做一个总结

首先开门见山,总结一下这三者的区别:

event.stopPropagation():阻止事件冒泡,对默认事件无影响

event.preventDefault():阻止默认事件,和事件冒泡无关

return false:原生js中,阻止默认事件,jQuery中既会阻止默认事件又会阻止事件冒泡

这样理解起来可能不是很清晰,我们都知道,a标签的默认事件之一为点击链接跳转,让我们做一个与此相关的小demo加深一下印象

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
div{width: 100px;height: 100px;border: 1px solid #ccc;}
div a{display: block;width: 30px;height: 100px;background: skyblue;}
</style>
</head>
<body>
<div id="box1">
<a href="http://www.baidu.com"></a>
</div>
<div id="box2">
<a href="http://www.baidu.com"></a>
</div>
<div id="box3">
<a href="http://www.baidu.com"></a>
</div>
<div id="box4">
<a href="http://www.baidu.com"></a>
</div>
<div id="box5">
<a href="#"></a>
</div>
<script>
/*event.stopPropagation()&&event.preventDefault()&&return false*/
box1.onclick=function(){
console.log("parent");
}//不阻止默认事件和冒泡,打印并且跳转

/*event.stopPropagtion(),阻止事件冒泡,但不影响默认事件*/
box2.onclick=function(){
console.log("parent");
}
box2.children[0].onclick=function(event){
event.stopPropagation();//仅跳转,冒泡被阻止
} /*event.preventDefault(),阻止默认事件,但冒泡不被阻止*/
box3.onclick=function(){
console.log("parent");
}
box3.children[0].onclick=function(event){
event.preventDefault();//打印parent,不跳转
} /*return false; 在原生中,该方法仅会阻止默认事件,相当于调用了event.preventDefault(),但在jQuery中,它
会同时阻止事件冒泡和默认事件*/
box4.onclick=function(){
console.log("parent");
}
box4.children[0].onclick=function(){
return false;
}</script> </body>
</html>