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

2022-01-18 00:00:00 tags click html anchor

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

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/

相关文章