18

请看这里: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属性是一个布尔属性。见这里

4

3 回答 3

36

做就是了

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');
}

disabledas 属性和disabledas 属性是不同的。

于 2013-07-11T17:42:49.570 回答
8

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

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

function disable() {
    document.getElementById("check").disabled = true;
}

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

于 2013-07-11T17:43:46.623 回答
4

有用,

 x.removeAttribute("disabled");

http://jsfiddle.net/maximos/89wxX/1/

于 2013-07-11T17:47:19.213 回答