简体   繁体   English

为什么需要在jquery中为.click函数设置“return false”语句

[英]why does there need to be a “return false” statement for the .click function in jquery

Example: 例:

$("#testdiv").click( function( )
 {
     $("#testdiv2").show( "slow" );
     return false;  // why is this statement required?
 } );

return false; will prevent the anchor tag from doing its default action 将阻止锚标记执行其默认操作

a jQuery-alternative would be to preventDefault() 一个jQuery替代方案是preventDefault()

$("#testdiv").click(function(e) {
    e.preventDefault();
    $("#testdiv2").show("slow");
});

returning false on an event hander does two things: 在事件处理中返回false会做两件事:

  1. If you have an anchor tag it will prevent anchor from following the link 如果你有一个锚标记,它将阻止锚点跟随链接

  2. It will stop event propagation (bubbling). 它将停止事件传播(冒泡)。 For example 例如

     < div id='outer' onclick="alert('hello')" > < div id='inner'> <!-- Your stuff --> < /div> < /div> 

    and

     $("#inner").click(function(event){ // Your code return false }) 

If your function returns false the alert("hello") wont get called when someone clicks the inner div. 如果你的函数返回false,当有人点击内部div时,不会调用alert("hello") Returning false is the same as calling both 返回false与调用两者相同

event.preventDefault();
event.stopPropagation();

A word of warning, this behavior only works with jquery 一句警告,此行为仅适用于jquery

event.preventDefault() vs. return false event.preventDefault()与return false

Source: John Resig 资料来源: John Resig

Without returning, anchor tag will do whatever it normally does. 没有返回,锚标记将执行它通常做的任何事情。 For instance, if you do <a href="#"> , it'll scroll to the top of the page. 例如,如果您执行<a href="#"> ,它将滚动到页面顶部。 Since some browsers don't treat as special unless/until there's an 'href' property, <a href="#"> is the most common way to make javascript action links. 由于某些浏览器不会视为特殊,除非/直到有'href'属性, <a href="#">是制作javascript操作链接的最常用方法。

There's no requirement to return false with jQuery's click event handler. 使用jQuery的click事件处理程序不需要返回false。 It is only required if you want to prevent the default anchor action from taking place. 只有在您希望阻止默认锚操作发生时才需要它。 If you want to do manipulation while still allowing the default action to take place, eg update location.hash with a new identifier <a href="#somelocation">click</a> and then doing something with the click event, then you wouldn't be required to supply a return false; 如果你想在仍然允许默认操作的情况下进行操作,例如使用新标识符<a href="#somelocation">click</a>更新location.hash然后对点击事件做一些事情,那么你不需要提供return false; .

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM