javascript之如何动态启用禁用的复选框
kuangbin
阅读:1048
2023-11-05 18:46:41
评论:0
请看这里: 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);
回答
正如答案所说,这是因为 disabled
属性是一个 bool 属性。 参见 here .
请您参考如下方法:
就这样
function enable() {
document.getElementById("check").disabled= false;
}
function disable() {
document.getElementById("check").disabled= true;
}
这样你就可以设置 DOM 元素的属性,同时设置属性的属性 disabled
将禁用复选框,所以即使你这样做 x.setAttribute("disabled", "false");
它仍将作为属性存在于元素上。
或者你会这样做:
function disable() {
document.getElementById("check").setAttribute('disabled', 'disabled');
}
function enable() {
document.getElementById("check").removeAttribute('disabled');
}
disabled
作为属性和 disabled
作为属性是不同的。
声明
1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。