如何在点击锚链接时停止跳转? [英] How to stop the jump when clicking on an anchor link?

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

问题描述

有没有办法在点击锚链接时避免跳转?

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

推荐答案

对这个问题最语义和最有意义的方法是处理onclick事件在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
$ b如果您已经使用JavaScript库$ b在您的锚点中包含一个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/

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆