jQuery 如何启用/禁用锚标记
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16657351/
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 enable/disable Anchor Tag
提问by Kiran Nunna
Below example is working for enable/disable of href but not for onclick. I need to enable/disable for both attributes
下面的示例适用于启用/禁用 href 但不适用于onclick。我需要启用/禁用这两个属性
Note: I cant simply remove/bind the onclick event to dummy function() as it need once we enable it.
注意:一旦我们启用它,我就不能简单地将 onclick 事件删除/绑定到虚拟函数(),因为它需要。
Script Code:
脚本代码:
<script type="text/javascript">
$(document).ready(function () {
$("#b1").click(function () {
$("#yahoo").attr("disabled", "disabled");
$("#yahoo").css("background-color", "silver");
})
$("#b2").click(function () {
$("#yahoo").removeAttr("disabled");
$("#yahoo").css("background-color", "white");
})
$("#yahoo").click(function (e) {
if ($("#yahoo").attr("disabled") == "disabled") {
e.preventDefault();
}
});
});
</script>
HTML Code:
HTML代码:
<div>
<input type="button" id="b1" value="Disable Yahoo Link">
<input type="button" id="b2" value="Enable Yahoo Link">
</div>
<a id="yahoo" target="_blank" href="javascript:alert('href alert')" onclick="javascript:alert('onclick alert')">Yahoo.com</a>
Working Example http://jsfiddle.net/nunnakirankumar/suYe4/
回答by parity3
Inside your click() function, you need to explicitly return false (after discovering it's disabled). Otherwise the default handler will cause the browser to go to or run the designated href.
在 click() 函数中,您需要明确返回 false(在发现它被禁用后)。否则默认处理程序将导致浏览器转到或运行指定的 href。
The OP has most likely moved on, so this answer is really just for google searchers' sake.
OP 很可能已经离开了,所以这个答案真的只是为了谷歌搜索者的缘故。