Href=“#” Don't Scroll

后端 未结 11 2259
暗喜
暗喜 2020-12-05 01:55

I am pretty new to JS - so just wondering whether you know how to solve this problem.

Current I have in my code



        
相关标签:
11条回答
  • 2020-12-05 02:15

    The easiest way to solve this problem is to just add another character after the pound symbol like this:

    <a href='#a' class="closeLink">close</a>
    

    Problem solved. Yes, it was that easy. Some may hate this answer, but they cannot deny that it works.

    Just make sure you don't actually have a section assigned to "a" or it will go to that part of the page. (I don't see this as often as I use to, though) "#" by itself, by default, goes to the top of the page.

    0 讨论(0)
  • 2020-12-05 02:15

    JavaScript version:

    myButton.onclick=function(e){
        e.preventDefault();
        // code
        return false;
    }
    

    jQuery version:

    $('.myButtonClass').click(function(e){
        e.preventDefault();
        // code
        return false;
    });
    

    This just do the job well! :)

    0 讨论(0)
  • 2020-12-05 02:21

    Although it seems to be very popular, href='#' is not a magic keyword for JavaScript, it's just a regular link to an empty anchor and as such it's pretty pointless. You basically have two options:

    1. Implement an alternative for JavaScript-unaware user agents, use the href parameter to point to it and cancel the link with JavaScript. E.g.:

      <a href="close.php" onclick="close(); return false">

    2. When the noscript alternative is not available or relevant, you don't need a link at all:

      <span onclick="close(); return false">Close</span>

    0 讨论(0)
  • 2020-12-05 02:21

    Use href = "JavaScript:Void(0);"

    0 讨论(0)
  • 2020-12-05 02:22

    return false is the answer, but I usually do this instead:

    $('.closeLink').click( function(event) {
          event.preventDefault();
          ...do the close action...
    });
    

    Stops the action from happening before you run your code.

    0 讨论(0)
  • 2020-12-05 02:25

    If your code is getting passed the eventObject you could use preventDefault(); returning false also helps.

    mylink.onclick = function(e){
     e.preventDefault();
     // stuff
     return false;
    }
    
    0 讨论(0)
提交回复
热议问题