如何动态启用禁用的复选框? [英] How to enable a disabled checkbox dynamically?
问题描述
请在此处查看: http://jsfiddle.net/nShQs/
按禁用按钮,然后按启用按钮.该复选框未启用.
HTML:
<input id="check" type="checkbox"/>
<input id="btn1" type="button" value="enable" />
<input id="btn2" type="button" value="disable" />
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
如答案所示,这是因为disabled
属性是布尔属性.
请参见此处.
只需
function enable() {
document.getElementById("check").disabled= false;
}
function disable() {
document.getElementById("check").disabled= true;
}
通过此操作,您可以设置DOM元素的属性,而设置属性disabled
的属性存在将禁用该复选框,因此,即使您执行x.setAttribute("disabled", "false");
,它仍将作为属性存在于元素上. /p>
或者您会这样做:
function disable() {
document.getElementById("check").setAttribute('disabled', 'disabled');
}
function enable() {
document.getElementById("check").removeAttribute('disabled');
}
disabled
作为属性和disabled
作为属性是不同的.
Please see here: http://jsfiddle.net/nShQs/
Press the disable button and then the enable button. The checkbox doesn't get enabled.
HTML:
<input id="check" type="checkbox"/>
<input id="btn1" type="button" value="enable" />
<input id="btn2" type="button" value="disable" />
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.
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.
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.
这篇关于如何动态启用禁用的复选框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!