首页 技术 正文
技术 2022年11月10日
0 收藏 312 点赞 2,949 浏览 1559 个字

做小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" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" ></a>
</div>
<div id="box2">
<a href="http://www.baidu.com" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" ></a>
</div>
<div id="box3">
<a href="http://www.baidu.com" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" ></a>
</div>
<div id="box4">
<a href="http://www.baidu.com" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" ></a>
</div>
<div id="box5">
<a href="#" rel="external nofollow" ></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>
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,492
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,907
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,740
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,494
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:8,132
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:5,295