使用 jQuery 防止点击操作 [英] Prevent onclick action with jQuery
问题描述
有一些带有 onclick 事件操作的链接
there are some links with onclick event actions
<a href="#" onclick="alert('panic!')">Let's panic</a>
<a href="#" onclick="alert('panic!')" disabled="disabled">I can't panic no more</a>
我需要防止在具有禁用属性的链接上执行事件操作而不删除点击操作.
I need prevent event actons execution on links with disabled attribute without removing onclick actions.
$('a[disabled]').click(function(e){
e.stopPropagation();
return false;
});
此代码对我没有帮助.
更新即使这段代码也不起作用
update Even this code doesn't work
<html><head><script type='text/javascript' src='jquery-1.3.2.js'></script></head>
<body>
<a href='#' onclick="alert('HA-ha!')" disabled="disabled" class="disabled">TEST</a>
<script type="text/javascript">
$('a[disabled], a.disabled').click(function(e){
console.log('override?');
e.stopImmediatePropagation();
e.preventDefault();
e.stopPropagation();
return false;
});
</script>
</body></html>
推荐答案
jQuery 不会解决这个 OOTB.它可以提供帮助,但 stopPropagation
、stopImmediatePropagation
、preventDefault
、return false
都不起作用,如果您只是附加它们到元素.您需要覆盖元素的点击处理程序.
jQuery is not going to solve this one OOTB. It can help, but none of stopPropagation
, stopImmediatePropagation
, preventDefault
, return false
will work if you simply attach them to the element. You need to override the element's click handler.
但是您在问题中声明不删除点击操作".因此,您需要在触发事件时覆盖默认行为(与简单地 null
为禁用的锚点删除 onclick
属性的更简洁方法相反):
However you state in your question "without removing onclick actions". So you need to override the default behavior at the point the event is triggered, (as opposed to the cleaner approach of simply null
ing out the onclick
attribute for disabled anchors):
我的意思是:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<title>Disable clicks</title>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
</head>
<body>
<a href="#" onclick="alert('panic!')">Let's panic</a>
<a href="#" onclick="alert('panic!')" disabled="disabled">I can't panic no more</a>
<script>
$('a[onclick]').each(function(){
$(this).data('onclick', this.onclick);
this.onclick = function(event) {
if($(this).attr('disabled')) { // HERE
return false;
};
$(this).data('onclick').call(this, event || window.event);
};
});
</script>
</body>
</html>
那里的方法是用抢占式逻辑覆盖内联点击处理程序 (onclick
) 以捕获锚点被禁用"的情况,然后然后取消事件(return false
).
The approach there is to override the inline click handler (onclick
) with preemptive logic to catch the case where the anchor is "disabled" and then cancel the event (with return false
).
这样做的好处是要再次启用锚点,您只需 .removeAttr('disabled')
就可以了.
The benefit there is that to enable an anchor again you simply .removeAttr('disabled')
on it.
这篇关于使用 jQuery 防止点击操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!