Avoid window jump to top when clicking #-links

后端 未结 12 1118
礼貌的吻别
礼貌的吻别 2020-11-27 21:32

I\'ve got a page with some questions and answers, the answers are collapsed by default. When they click the question I expand the hidden answer-div. The problem is that when

相关标签:
12条回答
  • 2020-11-27 22:06

    You are looking for event.preventDefault (see jQuery API).

    $(...).click(function(e) {
      e.preventDefault();
      // your code
    });
    
    0 讨论(0)
  • 2020-11-27 22:10

    You need to add preventDefault() to your click handler. This will stop the browser executing it's own link handler, and will only run the code you specify.

    Example:

    $("#myID").click(function(e) {
        e.preventDefault();
        // Do your stuff
    });
    
    0 讨论(0)
  • 2020-11-27 22:10

    If you add a "\" to the "#" it will prevent from going to the top.

    <a href="#\" id="myID">Myquestion</a>
    
    0 讨论(0)
  • 2020-11-27 22:14

    HTML:

    <a id="like-post" href="#\">like</a>
    

    JavaScript:

    $('body').delegate('#like-post','click',function(e) {
         e.preventDefault();
         .....
    });
    
    0 讨论(0)
  • 2020-11-27 22:15

    $('body').on('click', '[href^=#]', function (e) { e.preventDefault() });

    if the selector ex.."body" is there during the initial render then use the any selector .. id ... to target the general to have jQuery (as of 1.8.2) iterate over. the "On handler invoke a method called "bind" which is used for newly added content to the DOM",. Using the "[href^=#] will select any href that are in the section tag but you can replace section with anything or nothing and it applies a cancellation to the click event. This technique is great for dynamically created content to the DOM

    0 讨论(0)
  • 2020-11-27 22:17

    Inside your function of:

    And I've used jQuery and .click as event-listener.
    

    Will look something like:

    $("#myID").click(function(){});
    

    Change this to (don't forget the param e inside function(e):

    $("#myID").click(function(e){
        e.preventDefault();
    });
    
    0 讨论(0)
提交回复
热议问题