How to stop the jump when clicking on an anchor link? [duplicate]

ⅰ亾dé卋堺 提交于 2019-11-30 23:05:41

问题


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>


来源:https://stackoverflow.com/questions/9078817/how-to-stop-the-jump-when-clicking-on-an-anchor-link

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!