在 HTML 中显式设置 disabled="false" 不起作用

Explicitly set disabled="false" in the HTML does not work

我想在 html 文件 中明确将按钮设置为启用 。原因是我的代码稍后将按钮切换为禁用,如果代码崩溃,我可能会看到按钮被禁用。

我可以用

禁用按钮
$("#btn").attr("disabled","true")

然后 html 包含:

<button id="btn" disabled="false">I want to be enabled!</button>

按钮仍然显示为禁用状态。 检查员显示:

<button id="btn" disabled="">I want to be enabled!</button>

我知道我能做到

$("#btn").removeAttr("disabled") 

或类似的,但是对于 html.

中的许多元素这样做并不方便

HTML 不对布尔属性使用布尔值,令人惊讶。

在 HTML 中,布尔属性通过仅添加属性名称或(尤其是在 XHTML 中)使用属性名称作为其值来指定。

<input type="checkbox" disabled>                 <!-- HTML -->
<input type="checkbox" disabled />               <!-- Also HTML -->
<input type="checkbox" disabled="disabled" />    <!-- XHTML and HTML -->

这记录在 HTML 规范中:http://www.w3.org/TR/html5/infrastructure.html#boolean-attribute

A number of attributes are boolean attributes. The presence of a boolean attribute on an element represents the true value, and the absence of the attribute represents the false value.

The values "true" and "false" are not allowed on boolean attributes. To represent a false value, the attribute has to be omitted altogether.


更令人困惑的是,在 DOM 中,这些布尔属性 用布尔值指定的,例如:

/** @type HTMLInputElement */
const inputElement = document.createElement('input');

inputElement.disabled = true; // <-- The DOM *does* use a proper boolean value here.
console.log( inputElement.disabled ); // Prints "true"

inputElement.disabled = false;
console.log( inputElement.disabled ); // Prints "false"

...添加 更多 混淆 - 由于 JavaScript 的 falsyness - 使用字符串值属性 不会像您预期的那样工作:

inputElement.disabled = 'true';
console.log( inputElement.disabled ); // Prints "true"

inputElement.disabled = 'false';
console.log( inputElement.disabled ); // *Still* prints "true"

(这​​是因为JavaScript字符串'false'没有类型强制到JavaScript布尔值false ).


此外,某些 HTML 属性确实具有 truefalse 作为可能的值,例如 contentEditable(其中也有 inherit 作为第三个选项),还可以考虑 <form autocomplete="">,它可以是 onoff(以及许多其他值),这也可能使一些人感到困惑。 我认为一些遗留的(Internet Explorer 4.0 时代)扩展如 <object><applet> 可能有布尔值属性,并且在它们的子 <param value=""> 属性中肯定有布尔值,那是在这一点上只是一个历史的好奇心)。

如果您使用的是 AngularJS,请尝试使用 ng-disabled。在这种情况下,您可以使用类似的东西:

ng-disabled="true"
ng-disabled="false"
ng-disabled={{expression}}

它按预期工作....

我知道这是一个老话题,但由于没有明确的答案,这有帮助吗?这确实回答了明确标记为已启用的问题。

<button enabled>My Text</button>
<!-- Which also works as: -->
<button enabled="enabled">My Text</button>

我也在调查这个用于在验证发生时启用按钮。我希望这对某人有所帮助。

以后能帮到别人。

selectLanguage.onchange = function() {
    var value = selectLanguage.value;
    if (value != '') {
        submitLanguage.removeAttr('disabled');
    } else {
        submitLanguage.attr('disabled', 'disabled');
    }
    // submitLanguage.attr('enabled', 'enabled');
}

2022 年,如果您使用 EJS 或 Vue,则应将其设置为:

EJS:

<div <%=true?'enabled':'disabled'%> ></div>

视觉:

<div :disabled="someFuncInMethods()"></div>