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

from: http://css-tricks.com/return-false-and-prevent-default/

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 butnot 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:

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.



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值