jQuery 在 SPAN 元素上禁用设置属性不会阻止单击事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6657545/
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
Setting attribute disabled on a SPAN element does not prevent click events
提问by Petar Maymounkov
I have a <span>
element which does something on a click event.
我有一个<span>
元素可以在点击事件上做一些事情。
When I disable it, using jQuery:
当我禁用它时,使用 jQuery:
$("span").attr("disabled", true);
The event handler continues to be called when I click on the span element.
当我单击 span 元素时,将继续调用事件处理程序。
I am testing in Chrome 13. Any thoughts?
我正在 Chrome 13 中进行测试。有什么想法吗?
回答by David Espino
Try this:
尝试这个:
$("span").css("pointer-events", "none");
you can enabled those back by
你可以通过
$("span").css("pointer-events", "auto");
回答by You
The disabled
attribute is not global and is only allowed on form controls. What you coulddo is set a custom data attribute (perhaps data-disabled
) and check for that attribute when you handle the click event.
该disabled
属性不是全局的,只允许在表单控件上使用。您可以做的是设置自定义数据属性(可能data-disabled
)并在处理单击事件时检查该属性。
回答by Justin ??????
The disabled attribute's standard behavior only happens for form elements. Try unbinding the event:
disabled 属性的标准行为只发生在表单元素上。尝试解除绑定事件:
$("span").unbind("click");
回答by Rafay
回答by Mohit
There is a dirty trick, what I have used:
有一个肮脏的把戏,我用过的:
I am using bootstrap, so I just added .disabled
class to the element which I want to disable. Bootstrap handles the rest of the things.
我正在使用引导程序,所以我只是向.disabled
要禁用的元素添加了类。Bootstrap 处理其余的事情。
Suggestion are heartily welcome towards this.
衷心欢迎对此提出建议。
Adding class on run time:
在运行时添加类:
$('#element').addClass('disabled');
回答by ashik
The best method is to wrap the span inside a button and disable the button
最好的方法是将 span 包裹在按钮内并禁用按钮
$("#buttonD").click(function(){
alert("button clicked");
})
$("#buttonS").click(function(){
alert("span clicked");
})
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" />
<button class="btn btn-success" disabled="disabled" id="buttonD">
<span>Disabled button</span>
</button>
<br>
<br>
<span class="btn btn-danger" disabled="disabled" id="buttonS">Disabled span</span>