问题
I have a disabled button that should become enabled when there is text in an input element. The code to enable/disable the button is in the onblur
event of the input. My HTML consists of an input
with id="in"
, a button
with attribute disabled="disabled"
and a span
with id="sp"
.
$(document).ready(function(){
var count = 0;
$("#in").bind("blur",function(){
alert("blur");
if($("#in").attr("value").length > 0){
$("button")[0].disabled = false;
} else {
$("button")[0].disabled = true;
}
});
$("#in").bind("focusout",function(){
alert("focusout");
if($("#in").attr("value").length > 0){
$("button")[0].disabled = false;
} else {
$("button")[0].disabled = true;
}
});
$("button").click(function(){
count++;
$("#sp").text(count);
});
});
In IE 9, if I type text into the input element and click on the disabled button, the input's onblur
fires, the button becomes enabled, and I get the button's click event.
However, in Chrome, when I type text into the input element and click on the disabled button, nothing at all happens.
Is there some property of the button I'm overlooking? I tried to get the focusout
to fire, but I get the same result. I also get the same result using Firefox. Chrome seems to treat the disabled
attribute more strictly than IE, but this is going to cause problems with our users. How can I get the onblur
(or some equivalent) event to fire when I click off the input element onto a disabled button?
回答1:
In Chrome, disabled buttons have all event listeners removed from them. Clicking, right clicking, selectstarting, etc. doesn't work on disabled buttons. This means that the focus doesn't leave the input when you click the disabled button. What you can do is manually disable the button via class="disabled"
, and adding some styles to make it look disabled. Here is an example of CSS you could use to make the button look disabled:
button.disabled,
button.disabled:hover,
button.disabled:active,
button.disabled:focus {
color:gray;
background:#EEE;
border:1px solid #AAA;
border-radius:3px;
outline:none;
}
I've made a JSFiddle that shows this here. Also note that I've changed the code that toggles the disabled class now, instead of the disabled attribute, and I've put an if
statement in your button click event handler, so that it doesn't fire when the button is disabled.
来源:https://stackoverflow.com/questions/20859978/onblur-event-doesnt-fire-in-chrome-when-clicking-on-disabled-button-element-w