How to stop the jump when clicking on an anchor li

2019-02-16 12:17发布

问题:

This question already has an answer here:

  • Avoid window jump to top when clicking #-links 12 answers

Is there a way of avoiding the jump when clicking on an anchor link? So that the view does not change.

回答1:

The most semantic and meaningful approach to this problem would be to handle the onclick event from within JavaScript. Ideally this file would be best to be stored in a seperate file, however, including a in-line script within your problem file would suffice. Here's how i'd recommended approaching this problem if your already using a JavaScript library like jQuery.

Assign an ID
Include an id attribute to your anchor so it's able to be selected using jQuery:

<a href="#anchor" id="mylink" title="Title Here">Link Text</a>

Bind click event
From within your JavaScript file / in-line script include the following:

$('#mylink').click(function(event) {

    // This will prevent the default action of the anchor
    event.preventDefault();

    // Failing the above, you could use this, however the above is recommended
    return false;

});

The method above is explained in full using the jQuery API websites: http://api.jquery.com/event.preventDefault/



回答2:

Just use:

<a href="javascript:void(0);">Text</a>


回答3:

You could use Javascript to prevent the default behaviour of the link, a simple example being:

<a href="#myanchor" onclick="return false;">link</a>