是一个布尔属性,仅它的存在就会导致元素被禁用,无论该属性的值实际是多少。这就是为什么您可以通过将属性设置为来禁用JavaScript中的元素true
的原因,您可以将其设置为任何值(这就是为什么将其设置为false
禁用状态的原因)。
<input type="button" value="I'm disabled" disabled="true">
<input type="button" value="I'm disabled" disabled="false">
<input type="button" value="I'm disabled" disabled="doesn't matter">
<input type="button" value="I'm disabled" disabled="">
<input type="button" value="I'm disabled" disabled>
但是,建议使用布尔属性的约定(如果您确实想为属性提供值),以便我们在开发人员之间具有一定的一致性,那就是将其值设置为等于属性名称本身。因此,要禁用JavaScript中的元素,请遵循建议的约定:
element.setAttribute("disabled", "disabled");
element.removeAttribute("disabled");
document.querySelector("input[type='button']").removeAttribute("disabled");
<input type="button" value="I'm NOT disabled" disabled="disabled">
现在,在JavaScript中使用DOM对象时,有两种方法可以影响 并且了解使用这两种技术的效果非常重要:
这可能会造成混淆,但是HTML状态是元素从外部看起来的样子,而属性状态是内部真正发生的事情,例如您可以戴上笑脸,以便看着您的人认为您很高兴( HTML状态),但实际上您可能对真实状态(属性状态)感到难过。
如果尚未设置属性状态,那么属性状态就很重要,并且将完全控制元素的状态。设置属性状态后,它会覆盖任何可能的属性状态,并控制元素的实际状态。
// Get a reference to the button
var btn = document.querySelector("[type=button]");
// Test what the current HTML state is:
console.log(btn.getAttribute("disabled"));
// Test what the current mapped property state is:
console.log(btn.disabled);
// Change the property state, which will override the HTML state and
// and cause it to become enabled.
btn.disabled = false;
// Test what the current HTML state is:
console.log(btn.getAttribute("disabled")); // null because property overrode HTML
// Test what the current mapped property value is:
console.log(btn.disabled);
<input type="button" value="I'm disabled" disabled="disabled">
从 :
要启用该元素,请完全忽略此属性,而不是将值设置为false
。