如何使用jQuery启用或禁用锚点?
preventDefault()
。// jQuery 1.7+
$(function () {
$('a.something').on("click", function (e) {
e.preventDefault();
});
});
// jQuery < 1.7
$(function () {
$('a.something').click(function (e) {
e.preventDefault();
});
// or
$('a.something').bind("click", function (e) {
e.preventDefault();
});
});
参见:
http://docs.jquery.com/Events/jQuery.Event#event.preventDefault.28.29
此外,在SO上还可以查看此前的问题:
$('a.something').on("click", function (e) { e.preventDefault(); });
? - Incerteza我目前正在开发的应用程序使用CSS样式与JavaScript相结合来实现。
a.disabled { color:gray; }
然后每当我想要禁用一个链接时,我调用以下代码:
$('thelink').addClass('disabled');
然后,在'thelink' a标签的点击处理程序中,我总是首先运行一个检查。
if ($('thelink').hasClass('disabled')) return;
我找到了一个更好的答案在这里
看起来是这样的:
$(document).ready(function(){
$("a").click(function () {
$(this).fadeTo("fast", .5).removeAttr("href");
});
});
启用需要设置 href 属性。
$(document).ready(function(){
$("a").click(function () {
$(this).fadeIn("fast").attr("href", "http://whatever.com/wherever.html");
});
});
这将使锚点元素看起来像普通文本,反之亦然。
所选答案不好。
使用 CSS 样式 pointer-events。(如 Rashad Annara 建议)
请参考 MDN 文档 https://developer.mozilla.org/en-US/docs/Web/CSS/pointer-events。它在大多数浏览器中都受支持。
如果您有以下全局 CSS 规则,则简单地添加 "disabled" 属性到锚点即可完成任务:
a[disabled], a[disabled]:hover {
pointer-events: none;
color: #e1e1e1;
}
我认为更好的解决方案是在锚点上设置已禁用的数据属性并在单击时进行检查。这样,我们可以暂时禁用锚点,直到例如javascript完成ajax调用或某些计算。如果我们不禁用它,那么我们可能会快速点击它几次,这是不希望出现的...
$('a').live('click', function () {
var anchor = $(this);
if (anchor.data("disabled")) {
return false;
}
anchor.data("disabled", "disabled");
$.ajax({
url: url,
data: data,
cache: false,
success: function (json) {
// when it's done, we enable the anchor again
anchor.removeData("disabled");
},
error: function () {
// there was an error, enable the anchor
anchor.removeData("disabled");
}
});
return false;
});
我制作了一个jsfiddle的例子:http://jsfiddle.net/wgZ59/76/
$("a").click(function(){
alert('disabled');
return false;
});
尝试以下几行代码
$("#yourbuttonid").attr("disabled", "disabled");
$("#yourbuttonid").removeAttr("href");
因为即使你禁用了<a>
标签,href
仍然会起作用,所以你必须同时删除href
。
当你想启用时,请尝试以下几行:
$("#yourbuttonid").removeAttr("disabled");
$("#yourbuttonid").attr("href", "#nav-panel");
$('#divID').addClass('disabledAnchor');
在 CSS 文件中
.disabledAnchor a{
pointer-events: none !important;
cursor: default;
color:white;
}
这很简单,只需要写上 return false; 就可以了。
例如:
jQuery("li a:eq(0)").click(function(){
return false;
})
或者
jQuery("#menu a").click(function(){
return false;
})
$("a").click(function(event) {
event.preventDefault();
});