Html 如何动态启用禁用的复选框?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17599984/
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
How to enable a disabled checkbox dynamically?
提问by batman
Please see here: http://jsfiddle.net/nShQs/
请看这里:http: //jsfiddle.net/nShQs/
Press the disable button and then the enable button. The checkbox doesn't get enabled.
按禁用按钮,然后按启用按钮。复选框未启用。
HTML:
HTML:
<input id="check" type="checkbox"/>
<input id="btn1" type="button" value="enable" />
<input id="btn2" type="button" value="disable" />
JS:
JS:
function enable() {
var x = document.getElementById("check");
alert(x.getAttribute("disabled"));
x.setAttribute("disabled", "false");
alert(x.getAttribute("disabled"));
}
function disable() {
var x = document.getElementById("check");
alert(x.getAttribute("disabled"));
x.setAttribute("disabled", "true");
alert(x.getAttribute("disabled"));
}
document.getElementById("btn1").addEventListener("click", enable);
document.getElementById("btn2").addEventListener("click", disable);
answer
回答
As the answers tell it is because the disabled
attribute is a boolean attribute.
See here.
正如答案所说,这是因为该disabled
属性是一个布尔属性。见这里。
回答by PSL
Just do
做就是了
function enable() {
document.getElementById("check").disabled= false;
}
function disable() {
document.getElementById("check").disabled= true;
}
With this you are setting the property of the DOM element, while setting attribute presence of attribute disabled
will disable the check box, so even if you do x.setAttribute("disabled", "false");
it will still be there on the element as attribute.
有了这个,您正在设置 DOM 元素的属性,而设置属性的属性存在disabled
将禁用复选框,因此即使您这样做,x.setAttribute("disabled", "false");
它仍然会作为属性存在于元素上。
or you would just do:
或者你会这样做:
function disable() {
document.getElementById("check").setAttribute('disabled', 'disabled');
}
function enable() {
document.getElementById("check").removeAttribute('disabled');
}
disabled
as attribute and disabled
as property are different.
disabled
as attribute 和disabled
as property 是不同的。
回答by canon
Set the disabled
propertyrather than the attribute(fiddle).
设置disabled
属性而不是属性( fiddle)。
function enable() {
document.getElementById("check").disabled = false;
}
function disable() {
document.getElementById("check").disabled = true;
}
A control will remain disabled if the disabled
attributeis present at all- regardless of its value (fiddle). Setting the disabled
propertyto false
will remove the disabled
attribute.
如果该disabled
属性存在,则控件将保持禁用状态- 无论其值如何(fiddle)。将该disabled
属性设置为false
将删除该disabled
属性。