Heim > Web-Frontend > js-Tutorial > Hauptteil

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

WBOY
Freigeben: 2016-05-16 18:23:18
Original
1130 Leute haben es durchsucht

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:
return false;和e.preventDefault();的区别_javascript技巧
演示地址: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

测试代码打包下载

Verwandte Etiketten:
Quelle:php.cn
Erklärung dieser Website
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn
Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!