开发者

why does there need to be a "return false" statement for the .click function in jquery

Example开发者_C百科:

$("#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()

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


returning false on an event hander does two things:

  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. Returning false is the same as calling both

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

A word of warning, this behavior only works with jquery

event.preventDefault() vs. return false

Source: 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. 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.


There's no requirement to return false with jQuery's click event handler. 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, e.g. 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;.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜