如何使用 JavaScript 禁用锚点?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5552866/
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 anchor using JavaScript?
提问by krishna
I have to disable anchor link depending on a condition if some data comes to that field it should work as a hyperlink and if that data does not come then the link should not be there? Any ideas on this are welcome.
我必须根据条件禁用锚链接,如果某些数据进入该字段,它应该作为超链接工作,如果该数据没有出现,那么链接不应该在那里?欢迎对此提出任何想法。
回答by alex
I couldn't make sense of your question body, so I'll answer your question's title...
我无法理解你的问题主体,所以我会回答你的问题标题......
How to disable anchor using javascript ?
如何使用 javascript 禁用锚点?
JavaScript
JavaScript
if (condition) {
document.getElementsByTagName('a')[0].removeAttribute('href');
}
jQuery
jQuery
...because everyoneuses it, right?
...因为每个人都使用它,对吧?
if (condition) {
$('a').first().removeAttr('href');
}
回答by Jahid
Case 1:
情况1:
To disable:
要禁用:
document.getElementById(id).style.pointerEvents="none";
document.getElementById(id).style.cursor="default";
To enable:
启用:
document.getElementById(id).style.pointerEvents="auto";
document.getElementById(id).style.cursor="pointer";
Case 2:
案例2:
If you want the link to be gone (not just disable it):
如果您希望链接消失(不仅仅是禁用它):
document.getElementById(id).style.display="none";
to get it back:
取回它:
document.getElementById(id).style.display="block"; //change block to what you want.
Case 3:
案例3:
If you want to hide it preserving the space for it:
如果你想隐藏它,为它保留空间:
document.getElementById(id).style.visibility="hidden";
To get it back:
要取回它:
document.getElementById(id).style.visibility="visible";
回答by Mithun Sreedharan
with jQuery
使用 jQuery
if(!data){
$('#linkID').click(function(e) {
e.preventDefault();
});
}
with Prototype
带原型
if(!data){
$('linkID').observe('click', function(event) { event.stop() });
}
回答by anupam
<a href="javascript:check()">my link</a>
function check(){
var data =document.getElementById("yourdatafield").value;
if(data)
window.location="your_link_location";
}
回答by Maria
With jQuery:
使用 jQuery:
To disable:
要禁用:
$('#anchor_tag').attr("disabled", true);
To enable:
启用:
$('#anchor_tag').attr("disabled", false);