时间:2021-05-26
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
测试代码打包下载
声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。
取消默认操作w3c的方法是e.preventDefault(),IE则是使用e.returnValue=false;在支持addEventListener()的
方法一:$(document).on('touchmove',function(e){e.preventDefault();})方法二:position:fix
方法一:$('.shade').bind("touchmove",function(e){e.preventDefault();});方法二:$("body,.
点击元素后,滚动条滚动至该元素位置:$('a.lead-link').bind('click',function(e){e.preventDefault();$
我就废话不多说了,大家还是直接看代码吧~add:function(e){//阻止页面刷新e.preventDefault();//逻辑代码},补充知识:@sub