Setting attribute disabled on a SPAN element does

2020-02-08 05:01发布

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?

6条回答
疯言疯语
2楼-- · 2020-02-08 05:29

Try unbinding the event.

$("span").click(function(){
alert($(this).text());
    $("span").not($(this)).unbind('click');
});

Here is the fiddle

查看更多
对你真心纯属浪费
3楼-- · 2020-02-08 05:31

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.

查看更多
ゆ 、 Hurt°
4楼-- · 2020-02-08 05:35

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>

查看更多
家丑人穷心不美
5楼-- · 2020-02-08 05:36

The disabled attribute's standard behavior only happens for form elements. Try unbinding the event:

$("span").unbind("click");
查看更多
smile是对你的礼貌
6楼-- · 2020-02-08 05:36

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');
查看更多
仙女界的扛把子
7楼-- · 2020-02-08 05:38

Try this:

$("span").css("pointer-events", "none");

you can enabled those back by

$("span").css("pointer-events", "auto");
查看更多
登录 后发表回答