[英]Disable (and re-enable) the href and onclick on elements
I just want to enable / disable onclick and href on elements (a or div). 我只想在元素(a或div)上启用/禁用onclick和href。
I don't know how to do this. 我不知道该怎么做。
I can disable onclick by adding an handler on click event, but the href is still available. 我可以通过在click事件上添加处理程序来禁用onclick,但href仍然可用。
$(this).unbind().click(function(event){
event.preventDefault();
return;
});
Edit FOUND A HACK FOR A ELEMENTS 编辑找到了一个元素
if ($(this).attr("href")) {
$(this).attr("x-href", $(this).attr("href"));
$(this).removeAttr("href");
}
If you return false
on the onclick event, the href
is irgnored. 如果在onclick事件上返回
false
,则会忽略href
。
This will go to Goole: <a href="http://www.google.com" onclick="alert('Go to Google')">Test</a>
这将转到Goole:
<a href="http://www.google.com" onclick="alert('Go to Google')">Test</a>
This will not go to Google: <a href="http://www.google.com" onclick="alert('Go to Google'); return false;">Test</a>
这不会发给Google:
<a href="http://www.google.com" onclick="alert('Go to Google'); return false;">Test</a>
好吧,我找到了一个解决方法:在主div上放置一个叠加层,其中包含我想要禁用的所有元素..它只是有效。
You could try the following: 您可以尝试以下方法:
$('a, div').click(
function(e){
return false;
// cancels default action *and* stops propagation
// or e.preventDefault;
// cancels default action without stopping propagation
});
MDC documentation for preventDefault
, jQuery documentation for event.preventDefault
. preventDefault
MDC文档 , event.preventDefault
jQuery文档 。
SO question: JavaScript event.preventDefault
vs return false
. 所以问题:JavaScript
event.preventDefault
vs return false
。
I'm unsure as to the problem of the " href
still being available," since the click
event is cancelled; 由于
click
事件被取消,我不确定“ href
仍然可用”的问题; however if you want to remove the href
from a
elements: 但是如果你想删除的
href
从a
元素:
$('a[href]').attr('href','#');
will remove them (or, rather, replace the URL with a #
). 将删除它们(或者更确切地说,用
#
替换URL)。
Edited in response to comment (to question) by OP: 编辑回应OP的评论(提问):
Ok, sorry ;) I just want to be able (by clicking on a button), to disable / enable all the links (click or href) over elements (div or a)
好的,对不起;)我只想(通过点击一个按钮),禁用/启用所有链接(点击或href)元素(div或a)
$('#buttonRemoveClickId, .buttonClassName').click(
function() {
$('a, div').unbind('click');
});
$('#buttonReplaceClickId, .buttonOtherClassName').click(
function() {
$('a, div').bind('click');
});
Try this to disable click: 试试这个来禁用点击:
$(this).unbind('click'); $(本).unbind( '点击');
You can set the href
attribute directly to ""
to prevent the original from showing up in the status bar, if that's what you're asking. 您可以将
href
属性直接设置为""
以防止原始文件显示在状态栏中,如果这是您要求的。
$(this).unbind().click(function(event){
event.preventDefault();
}).attr("href", "");
Otherwise, a event.preventDefault()
already stops links from being clickable. 否则,
event.preventDefault()
已经阻止链接被点击。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.