javascript 如何通过Javascript根据条件禁用超链接
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11900863/
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
How to disable the hyperlink based on the condition through Javascript
提问by pavan
How to disable the hyperlink based on the condition
如何根据条件禁用超链接
var mydiv = document.getElementById("myDiv");
var aTag = document.createElement('a');
aTag.setAttribute('href',"yourlink.htm");
aTag.innerHTML = "link text";
mydiv.innerHTML="";
mydiv.innerHTML=aTag;
say i need to disable my aTag here.
说我需要在这里禁用我的 aTag。
Based on logged on user i need to disable or enable..
根据登录用户,我需要禁用或启用..
回答by Tim Medora
You can disable the link by setting the disabled attribute (not valid on anchor elements, though it works in some cases).
您可以通过设置 disabled 属性来禁用链接(在锚元素上无效,但它在某些情况下有效)。
Test setup for disabled attribute on anchors: http://jsfiddle.net/TgjnM/
锚上禁用属性的测试设置:http: //jsfiddle.net/TgjnM/
Preferably, you can remove the link altogether and replace it with the text it contains. To replace the link with plain text, you would set the innerHTML of mydiv
to the text (thus removing the hyperlink).
最好,您可以完全删除该链接并将其替换为它包含的文本。要将链接替换为纯文本,您需要将 的innerHTML 设置mydiv
为文本(从而删除超链接)。
If the link can be toggled on/off, consider a form element (not a hyperlink) as @Oleg V. Volkov suggested in the comments. If it is a one-time decision (i.e. it won't be happening multiple times per page), I would replace the link with text.
如果链接可以打开/关闭,请考虑@Oleg V. Volkov 在评论中建议的表单元素(不是超链接)。如果这是一次性决定(即不会在每页发生多次),我会将链接替换为文本。
Based on logged on user i need to disable or enable..
根据登录用户,我需要禁用或启用..
In that case, I would render the page differently on the server, not in the web browser.
在这种情况下,我会在服务器上以不同的方式呈现页面,而不是在 Web 浏览器中。
回答by thecodeHyman
This should work
这应该工作
if(condition)
disableLink();
else
showLink();
function disableLink()
{
document.getElementById('Link1').disabled=true;
document.getElementById('Link1').removeAttribute('href');
document.getElementById('Link1').style.textDecoration = 'none';
document.getElementById('Link1').style.cursor = 'default';
}
function showLink()
{
document.getElementById('Link1').disabled=false;
//assign href dynamically
document.getElementById('Link1').href = "somepage.html";
document.getElementById("Link1").style.textDecoration = "underline";
document.getElementById("Link1").style.cursor = "hand";
}