return false;和e.preventDefault();的区别

所属分类: 网络编程 / JavaScript 阅读数: 1830
收藏 0 赞 0 分享
Have you ever seen those two things (in the title) being used in jQuery? Here is a simple example:
复制代码 代码如下:

$("a").click(function() {
$("body").append($(this).attr("href"));
return false;
}

That code would append the href attribute as text to the body every time a link was clicked but not actually go to that link. The return false; part of that code prevents the browser from performing the default action for that link. That exact thing could be written like this:
复制代码 代码如下:

$("a").click(function(e) {
$("body").append($(this).attr("href"));
e.preventDefault();
}

So what's the difference?


The difference is that return false; takes things a bit further in that it also prevents that event from propagating (or “bubbling up”) the DOM. The you-may-not-know-this bit is that whenever an event happens on an element, that event is triggered on every single parent element as well. So let's say you have a box inside a box. Both boxes have click events on them. Click on the inner box, a click will trigger on the outer box too, unless you prevent propagation. Like this:

演示地址:http://css-tricks.com/examples/ReturnFalse/
So in other words:
复制代码 代码如下:

function() {
return false;
}

// IS EQUAL TO

function(e) {
e.preventDefault();
e.stopPropagation();
}

It's all probably a lot more complicated than this and articles like this probably explain it all a lot better.


参考:

1.The difference between ‘return false;' and ‘e.preventDefault();'
2.Event order

测试代码打包下载

更多精彩内容其他人还在看

JavaScript this关键字指向常用情况解析

这篇文章主要介绍了JavaScript this关键字指向常用情况解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
收藏 0 赞 0 分享

Vue-cli打包后如何本地查看的操作

这篇文章主要介绍了Vue-cli打包后如何本地查看的操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
收藏 0 赞 0 分享

vue cli 3.0通用打包配置代码,不分一二级目录

这篇文章主要介绍了vue cli 3.0通用打包配置代码,不分一二级目录,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
收藏 0 赞 0 分享

JavaScript事件循环及宏任务微任务原理解析

这篇文章主要介绍了JavaScript事件循环及宏任务微任务原理解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
收藏 0 赞 0 分享

关于vue-cli3打包代码后白屏的解决方案

这篇文章主要介绍了关于vue-cli3打包代码后白屏的解决方案,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
收藏 0 赞 0 分享

vue打包静态资源后显示空白及static文件路径报错的解决

这篇文章主要介绍了vue打包静态资源后显示空白及static文件路径报错的解决,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
收藏 0 赞 0 分享

vue-cli3访问public文件夹静态资源报错的解决方式

这篇文章主要介绍了vue-cli3访问public文件夹静态资源报错的解决方式,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
收藏 0 赞 0 分享

JS继承实现方法及优缺点详解

这篇文章主要介绍了JS继承实现方法及优缺点详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
收藏 0 赞 0 分享

vue或react项目生产环境去掉console.log的操作

这篇文章主要介绍了vue或react项目生产环境去掉console.log的操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
收藏 0 赞 0 分享

解决vue组件没显示,没起作用,没报错,但该显示的组件没显示问题

这篇文章主要介绍了解决vue组件没显示,没起作用,没报错,但该显示的组件没显示问题,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
收藏 0 赞 0 分享
查看更多