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

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

问题描述

我有 HREF ONCLICK 属性设置的锚点。如果点击并启用Javascript,我只希望它执行 ONCLICK 并忽略 HREF 。同样,如果Javascript被禁用或不支持,我希望它遵循 HREF URL并忽略 ONCLICK 。下面是我正在做的一个例子,它会执行JS并且同时跟随链接(通常JS被执行,然后页面改变):

<$ p $ <> c $ c>< A HREF =http://example.com/no-js-loginONCLICK =yes_js_login()>登录< / A>

做这件事的最好方法是什么?



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

解决方案

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

 < a href =https: //example.com/no-js-loginonclick =return yes_js_login();>登录< / a> 

yes_js_login = function(){
//您的代码在这里
返回false;
}

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


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>

what's the best way to do this?

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.

解决方案

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;
}

Example: https://jsfiddle.net/FXkgV/289/

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

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