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

How to stop the jump when clicking on an anchor link?(单击锚链接时如何停止跳转?)

本文介绍了单击锚链接时如何停止跳转?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

推荐答案

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

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.

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

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

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;

});

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

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

这篇关于单击锚链接时如何停止跳转?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:单击锚链接时如何停止跳转?

基础教程推荐