jQuery - 根据条件禁用和启用锚标记
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19006299/
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
jQuery - disable and enable an anchor tag based on condition
提问by Mary
On page load, I am checking to see if a person is registered. If he is then, I will enable a link otherwise disable the link.
在页面加载时,我正在检查某人是否已注册。如果他在那时,我将启用一个链接,否则禁用该链接。
I tried the following , but it doesnt work.
我尝试了以下,但它不起作用。
var status = $('#status');
if (status == 'Registered'){
$('#addlink').data('disabled');
}
else {
}
回答by patb
An alternative based on CSS would be
基于 CSS 的替代方案是
$('#addlink').css('pointer-events', 'none');
CanIUse reports a 94% support of this feature as of early 2017.
CanIUse 报告称,截至 2017 年初,该功能的支持率为 94%。
回答by Tushar Gupta - curioustushar
use event.preventDefaultto prevent anchor tag to work.
使用event.preventDefault来防止锚标记工作。
anchor
tag doesn't disable on adding attribute disabled
anchor
添加属性时标签不会禁用 disabled
var status = $('#status').text(); // get text value if it's is span/div/p etc
if (status == 'Registered') {
$('#addlink').click(function (e) {
e.preventDefault();
});
}
回答by Anil kumar
Try this, if user is register then enable the link by adding href, if not then disable by removing the href attribute.
试试这个,如果用户已注册,则通过添加 href 启用链接,如果没有,则通过删除 href 属性禁用。
Just set the status
to some string
before executing this code.
只需在执行此代码之前将其设置status
为 some 即可string
。
var href = $('#addlink').attr('href');
if(status == 'Registered'){
$('#addlink').attr('href', href);
} else{
$('#addlink').removeAttr('href');
}
Check here.
检查这里。
回答by MichaC
If you really want to remove the link you can use jquery unwrap method.
如果你真的想删除链接,你可以使用 jquery unwrap 方法。
$("yourlinkselector").contents().unwrap();
This will remove the link. To add it back again you might have to put the link text into a span, give it a name and use .wrap to wrap it around your content.
这将删除链接。要再次添加它,您可能需要将链接文本放入一个跨度中,为其命名并使用 .wrap 将其包裹在您的内容中。
Working example can be found here: http://jsfiddle.net/Elak/hrvPj/2/
可以在这里找到工作示例:http: //jsfiddle.net/Elak/hrvPj/2/
// remove the link
$(".link").contents().unwrap().wrap("<span class='oldLink'></span>")
// add the link again and remove the temp span
$(".oldLink").contents().unwrap().wrap("<a href='#'></a>");
回答by pszaba
Why don't you use the javascript:void(0) ?
你为什么不使用 javascript:void(0) ?
<a href="javascript:void(0)"> Link </a>
like
喜欢
var href = 'javascript:void(0)';
var status = $('#status').val(); // ??
if (status == 'Registered'){
href = 'available link';
}
$('#addlink').attr('href',href);
回答by Praveen
var status = $('#status').val(); //Not sure if it is a value/text
$('#addlink').on('click', function (e) {
if (status == 'Registered') {
e.preventDefault(); // prevent the default action of anchor tag
return false;
}
});