作家
登录

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

作者: 来源:www.28hudong.com 2013-03-30 01:26:48 阅读 我要评论

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测试代码打包下载

  推荐阅读

  通过继承IHttpHandle实现JS插件的组织与管理

如: 复制代码 代码如下: <!— Js插件 --> <script type="text/javascript" src="/scripts/popup.js"></script> <script type="text/javascript" src="/scripts/popup-util.js"></script> <!—Jquery插件 --> <scr>>>详细阅读


本文标题:return false;和e.preventDefault();的区别

地址:http://www.17bianji.com/kaifa2/JS/26020.html

关键词: 探索发现

乐购科技部分新闻及文章转载自互联网,供读者交流和学习,若有涉及作者版权等问题请及时与我们联系,以便更正、删除或按规定办理。感谢所有提供资讯的网站,欢迎各类媒体与乐购科技进行文章共享合作。

网友点评
自媒体专栏

评论

热度

精彩导读
栏目ID=71的表不存在(操作类型=0)