[英]How to enable a disabled checkbox dynamically?
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. 正如答案所说,这是因为disabled
属性是一个布尔属性。 See here . 看到这里 。
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");
有了这个你设置DOM元素的属性,而设置属性的属性disabled
将禁用复选框,所以即使你做x.setAttribute("disabled", "false");
it will still be there on the element as attribute. 它仍将作为属性存在于元素上。
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
属性和disabled
属性不同。
Set the disabled
property rather than the attribute ( fiddle ). 设置disabled
属性而不是属性 ( 小提琴 )。
function enable() {
document.getElementById("check").disabled = false;
}
function disable() {
document.getElementById("check").disabled = true;
}
A control will remain disabled if the disabled
attribute is present at all - regardless of its value ( fiddle ). 如果disabled
属性完全存在,控件将保持禁用状态 - 无论其值( 小提琴 )如何。 Setting the disabled
property to false
will remove the disabled
attribute . 将disabled
属性设置为false
将删除disabled
属性 。
It works, 有用,
x.removeAttribute("disabled");
http://jsfiddle.net/maximos/89wxX/1/ http://jsfiddle.net/maximos/89wxX/1/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.