在JavaScript事件处理中,为什么“返回false”或“event.preventDefault()”和“停止事件流”会有所作为吗? [英] In JavaScript event handling, why "return false" or "event.preventDefault()" and "stopping the event flow" will make a difference?
问题描述
据说当我们处理一个点击事件时,返回false或者调用event.preventDefault()有所不同,其中
的区别在于,preventDefault
只会阻止默认事件
的动作发生,即链接点击,表单提交,
等页面重定向
返回false也将停止
事件流。
这是否意味着如果点击事件被注册了几次action(){...}
返回false会阻止其他处理程序运行?
我是在Mac上,因此只能使用Firefox和Chrome,而不是IE,它具有不同的事件模型,并通过添加3个处理程序在FF和Chrome上进行测试,并且所有3个处理程序都不会停止运行。那么真正的区别是什么呢,或者是否有停止事件流的情况是不可取的?
这与
使用jQuery的animate(),如果点击的元素是< a href =# ...> < / a>,该函数应该仍然返回false?
和
e.preventDefault()之间有什么区别?并返回false?
希望这段代码可以解释给你...
html
< div>
< a href =index.htmlclass =a1>点击我< / a>
< a href =index.htmlclass =a2>点击我< / a>
< / div>
jquery
$ $ $ $ $'$'''''''''''''''''''''''' ;
$('a.a1')。click(function(){
alert('我来自< a>');
return false; // this将产生一个警报
});
$('a.a2')。click(function(e){
alert('我来自< a>');
e.preventDefault() ; //这将产生两个警报
});
或
点击(function(){
alert('我来自< div>');
});
$('a')。click(function(){
alert('我来自< a>');
});
$('a.a1')。click(function(){
alert('我来自< a class =a1>');
return false;
});
$('a.a2')。click(function(e){
alert('我来自< a class =a2>');
e.preventDefault();
});
It is said that when we handle a "click event", returning false or calling event.preventDefault() makes a difference, in which
the difference is that preventDefault will only prevent the default event action to occur, i.e. a page redirect on a link click, a form submission, etc. and return false will also stop the event flow.
Does that mean, if the click event is registered several times for several actions, using
$('#clickme').click(function() { … })
returning false will stop the other handlers from running?
I am on a Mac now and so can only use Firefox and Chrome but not IE, which has a different event model, and tested it on FF and Chrome by adding 3 handlers, and all 3 handlers ran without any stopping…. so what is the real difference, or, is there a situation where "stopping the event flow" is not desirable?
this is related to
and
What's the difference between e.preventDefault(); and return false?
hopes this code can explain it to you...
html
<div>
<a href="index.html" class="a1">click me</a>
<a href="index.html" class="a2">click me</a>
</div>
jquery
$('div').click(function(){
alert('I am from <div>');
});
$('a.a1').click(function(){
alert('I am from <a>');
return false; // this will produce one alert
});
$('a.a2').click(function(e){
alert('I am from <a>');
e.preventDefault(); // this will produce two alerts
});
or
$('div').click(function(){
alert('I am from <div>');
});
$('a').click(function(){
alert('I am from <a>');
});
$('a.a1').click(function(){
alert('I am from <a class="a1">');
return false;
});
$('a.a2').click(function(e){
alert('I am from <a class="a2">');
e.preventDefault();
});
这篇关于在JavaScript事件处理中,为什么“返回false”或“event.preventDefault()”和“停止事件流”会有所作为吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!