如果执行 onclick,如何禁用 HREF? [英] How can I disable HREF if onclick is executed?

查看:29
本文介绍了如果执行 onclick,如何禁用 HREF?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有 HREFONCLICK 属性集的锚点.如果单击并启用 Javascript,我希望它执行 ONCLICK 并忽略 HREF.同样,如果 Javascript 被禁用或不受支持,我希望它遵循 HREF URL 并忽略 ONCLICK.下面是我正在做的一个例子,它会执行 JS 并同时跟踪链接(通常是执行 JS 然后页面发生变化):

I have an anchor with both HREF and ONCLICK attributes set. If clicked and Javascript is enabled, I want it to only execute ONCLICK and ignore HREF. Likewise, if Javascript is disabled or unsupported, I want it to follow the HREF URL and ignore ONCLICK. Below is an example of what I'm doing, which would execute the JS and follow the link concurrently (usually the JS is executed and then the page changes):

<A HREF="http://example.com/no-js-login" ONCLICK="yes_js_login()">Log in</A>

这样做的最佳方法是什么?

我希望得到一个 Javascript 答案,但我会接受任何有效的方法,特别是如果这可以用 PHP 完成.我读过ahref 链接在 javascript onclick 功能能够完成之前执行并重定向页面",但它只会延迟 HREF,但不会完全禁用它.我也在寻找更简单的东西.

I'm hoping for a Javascript answer, but I'll accept any method as long as it works, especially if this can be done with PHP. I've read "a href link executes and redirects page before javascript onclick function is able to finish" already, but it only delays HREF, but doesn't completely disable it. I'm also looking for something much simpler.

推荐答案

您可以使用第一个未编辑的解决方案,如果您将 return 放在 onclick 属性中:

You can use the first un-edited solution, if you put return first in the onclick attribute:

<a href="https://example.com/no-js-login" onclick="return yes_js_login();">Log in</a>

yes_js_login = function() {
     // Your code here
     return false;
}

示例:https://jsfiddle.net/FXkgV/289/

这篇关于如果执行 onclick,如何禁用 HREF?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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