Html 单击锚链接时如何停止跳转?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9078817/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 22:10:59  来源:igfitidea点击:

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

htmltagsclickanchor

提问by Tomkay

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

单击锚链接时有没有办法避免跳转?这样视图就不会改变。

回答by James

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.

解决这个问题的最语义和最有意义的方法是在 JavaScript 中处理 onclick 事件。理想情况下,这个文件最好存储在一个单独的文件中,但是,在问题文件中包含一个内嵌脚本就足够了。如果您已经在使用像 jQuery 这样的 JavaScript 库,那么我建议您如何解决这个问题。

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

分配一个 ID
为您的锚点包含一个 id 属性,以便可以使用 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:


在您的 JavaScript 文件/内嵌脚本中绑定点击事件包括以下内容:

$('#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/

使用 jQuery API 网站完整解释了上述方法:http: //api.jquery.com/event.preventDefault/

回答by Nirmal

Just use:

只需使用:

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

回答by James

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

您可以使用 Javascript 来阻止链接的默认行为,一个简单的例子是:

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