问题
I have a <span>
element which does something on a click event.
When I disable it, using jQuery:
$("span").attr("disabled", true);
The event handler continues to be called when I click on the span element.
I am testing in Chrome 13. Any thoughts?
回答1:
Try this:
$("span").css("pointer-events", "none");
you can enabled those back by
$("span").css("pointer-events", "auto");
回答2:
The disabled
attribute is not global and is only allowed on form controls. What you could do is set a custom data attribute (perhaps data-disabled
) and check for that attribute when you handle the click event.
回答3:
The disabled attribute's standard behavior only happens for form elements. Try unbinding the event:
$("span").unbind("click");
回答4:
Try unbinding the event.
$("span").click(function(){
alert($(this).text());
$("span").not($(this)).unbind('click');
});
Here is the fiddle
回答5:
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.
Suggestion are heartily welcome towards this.
Adding class on run time:
$('#element').addClass('disabled');
回答6:
The best method is to wrap the span inside a button and disable the button
$("#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>
来源:https://stackoverflow.com/questions/6657545/setting-attribute-disabled-on-a-span-element-does-not-prevent-click-events