“[removed]void(0);” vs “return false” vs “preventDefault()”

前端 未结 8 1230
滥情空心
滥情空心 2020-11-28 19:44

When I want some link to not do anything but only respond to javascript actions what\'s the best way to avoid the link scrolling to the top edge of the page ?
I know sev

相关标签:
8条回答
  • 2020-11-28 20:16

    I like using href="javascript:void(0)" in the link as # implies jumping to the top of the page and that may in fact happen if for some reason your jQuery event does not load e.g. jQuery fails to load.

    I also use event.preventDefault(); as it will not follow the link even if an error is encountered before return false; for example:

    HTML:

    <a id="link" href="http://www.google.com">Test</a>
    

    jQuery Example 1:

    $("#link").click(
        function(){
            alert("Hi");
            invalidCode();
            return false;
        }
    );
    

    jQuery Example 2:

    $("#link").click(
        function(event){
            event.preventDefault();
            alert("Hi");
            invalidCode();
            return false;
        }
    );
    

    Since invalidCode(); will throw an error return false is never reached and if jQuery Example 1 is used the user will be redirected to Google whereas in jQuery Example 2 he will not.

    0 讨论(0)
  • 2020-11-28 20:22

    I'd rather not put JavaScript into the href because that's not what it's meant for. I prefer something like

    <a href="#" onclick="return handler();">Link</a>
    
    0 讨论(0)
提交回复
热议问题