使用 javascript 禁用链接

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3929598/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 02:43:38  来源:igfitidea点击:

Disable link using javascript

javascriptdom

提问by Ybbest

I have following HTML and would like to disable the link using javascript.

我有以下 HTML 并想使用 javascript 禁用链接。

<a style="white-space: nowrap;" onclick="return InstallWebApp(true);" id="uc_ii_lnkInstall" href="javascript:__doPostBack('uc_ii$lnkInstall','')">
<img style="border-width: 0pt; margin-right: 3px;" id="uc_ii_lnkInstallImg" alt="Install" title="Install" src="/CortexDotNet/pics/buttons/install_g.gif">
Install
</a>

The JavaScript I am using are :

我使用的 JavaScript 是:

  document.getElementById("uc_ii_lnkInstall").disabled = true;

However , it does not work , I could still click this this link after I have disabled the link using the above javascript.I look at the html , it does not seem to have the disable attribute in the a tag.Can anyone help me to explain this please?

但是,它不起作用,在使用上面的 javascript 禁用链接后,我仍然可以单击此链接。我查看 html,它似乎在 a 标记中没有禁用属性。任何人都可以帮助我请解释一下?

回答by PleaseStand

document.getElementById("uc_ii_lnkInstall").onclick = function() { return false; };

The return value of false in the old-style event handler prevents the default action (i.e. loading the javascript: URL).

旧式事件处理程序中的 false 返回值阻止了默认操作(即加载 javascript: URL)。

If you want to gray out the image link, you would also need to swap out the image's src URL with one pointing to a grayed-out version of the icon and change the text's color using .style.color = "gray";.

如果您想让图片链接变灰,您还需要将图片的 src URL 替换为指向变灰版本的图标,并使用.style.color = "gray";.

回答by Shaoz

I don't think the 'disable' attribute will work on links, it work mostly on form elements such as inputs, textarea, button, etc.

我认为“禁用”属性不适用于链接,它主要适用于表单元素,例如输入、文本区域、按钮等。

But as @idealmachine said normal links <a>can be disabled by returning false 'return false' in javascript/jquery.

但正如@idealmachine 所说,<a>可以通过return false在 javascript/jquery 中返回 false ' '来禁用正常链接。