如何动态启用禁用复选框?

bat*_*man 16 html javascript

请看这里:http: //jsfiddle.net/nShQs/

按禁用按钮,然后按启用按钮.该复选框未启用.

HTML:

<input id="check" type="checkbox"/>
<input id="btn1" type="button" value="enable" />
<input id="btn2" type="button" value="disable" />
Run Code Online (Sandbox Code Playgroud)

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);
Run Code Online (Sandbox Code Playgroud)

回答

正如答案所说,这是因为该disabled属性是一个布尔属性.看到这里.

PSL*_*PSL 31

做就是了

function enable() {
    document.getElementById("check").disabled= false;

}

function disable() {
     document.getElementById("check").disabled= true;
}
Run Code Online (Sandbox Code Playgroud)

有了这个,你设置DOM元素的属性,而设置属性的属性disabled将禁用复选框,所以即使你这样做x.setAttribute("disabled", "false");仍然会在元素作为属性.

演示

或者你会这样做:

function disable() {
    document.getElementById("check").setAttribute('disabled', 'disabled');
}

function enable() {
   document.getElementById("check").removeAttribute('disabled');
}
Run Code Online (Sandbox Code Playgroud)

disabled属性和disabled属性是不同的.

  • 不常见,特别是对于这些布尔属性值,我会找到一个链接供您参考,attr和属性之间的差异 (2认同)
  • @learner一些其他属性(如`readonly`)的工作方式相同.这有点出乎意料,你偶然会偶然发现这些事情.也就是说,如果你坚持使用相应的属性,他们将抽象出奇怪的属性实现. (2认同)
  • @learner阅读最后一节:https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes (2认同)

I a*_*ica 7

设置disabled 属性而不是属性(小提琴).

function enable() {
    document.getElementById("check").disabled = false;    
}

function disable() {
    document.getElementById("check").disabled = true;
}
Run Code Online (Sandbox Code Playgroud)

如果disabled 属性存在,控件将保持禁用状态- 无论其值(小提琴)如何.将disabled 属性设置为false将删除该disabled 属性.