用户单击链接(< a>元素)时如何取消导航? [英] How to cancel navigation when user clicks a link (<a> element)?

查看:71
本文介绍了用户单击链接(< a>元素)时如何取消导航?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当用户单击链接时,我正在尝试使用AJAX加载某些内容,但我希望该链接实际位于某处,以便在禁用javascript时该应用程序仍能正常工作.有什么方法可以通过单击链接来使用javascript进行某些操作并取消导航吗?

I'm trying to load some stuff using AJAX when a user clicks a link, but I want the link to actually go somewhere so that the app still works when javascript is disabled. Is there any way to just do something with javascript and cancel navigation when a link is clicked?

最佳做法是什么?可以这样做,还是我需要使用javascript或其他替换链接?

What's the best practice? Can that be done, or do I need to replace the link using javascript or what?

推荐答案

如果您有这样的HTML:

If you have HTML like this:

<a href="no_javascript.html" id="mylink">Do Something</a>

您将使用jQuery做类似的事情:

You would do something like this with jQuery:

$(document).ready(function() {
    $('#mylink').click(function() {
        doSomethingCool();
        return false; // cancel the event
    });
});

您要做的就是用Java取消click事件,以防止发生默认操作.因此,当有人单击启用了Javascript的链接时,会调用doSomethingCool();并取消单击事件(因此是return false;),从而阻止浏览器转到指定的页面.但是,如果禁用了Javascript,则会直接将它们带到no_javascript.html.

All you have to do is cancel the click event with Javascript to prevent the default action from happening. So when someone clicks the link with Javascript enabled, doSomethingCool(); is called and the click event is cancelled (thus the return false;) and prevents the browser from going to the page specified. If they have Javascript disabled, however, it would take them to no_javascript.html directly.

这篇关于用户单击链接(&lt; a&gt;元素)时如何取消导航?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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