要删除disabled属性,请选择元素并调用其 removeAttribute()上的方法,将其disabled作为参数传递,例如 btn.removeAttribute('disabled'). 该removeAttribute方法将从元素中删除 disabled属性。

这是本文中示例的 HTML。

index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
  </head>

  <body>
    <button disabled id="btn">Button</button>

    <script src="index.js"></script>
  </body>
</html>

这是相关的 JavaScript 代码。

index.js
const btn = document.getElementById('btn');

// ✅ Remove disabled attribute from button
btn.removeAttribute('disabled');

// ✅ Add disabled attribute to button
// btn.setAttribute('disabled', '');

我们选择了button使用document.getElementById()方法。

然后我们使用 removeAttribute 方法从元素中删除disabled属性。

该方法将要删除的属性作为参数。

如果元素上不存在该属性,则该方法不会引发错误,它会忽略调用。 removeAttribute()

在设置布尔属性的值时,例如disabled,我们可以为该属性指定任何值,它将起作用。

如果该属性完全存在,则无论值如何,它的值都被认为是true

如果不存在诸如 的布尔属性,disabled则认为该属性的值是false

如果需要添加属性,可以使用setAttribute方法。

index.js

const btn = document.getElementById('btn');

// ✅ Remove disabled attribute from button
btn.removeAttribute('disabled');

// ✅ Add disabled attribute to button
btn.setAttribute('disabled', '');

该方法将属性名称作为第一个参数,将应分配给该属性的值作为第二个参数。

设置布尔属性时,例如disabled,最好将它们设置为空值。这就是为什么我们在示例中传递了一个空字符串作为值。

disabled属性可以设置为任何值,只要它存在于元素上,它就可以完成工作。

请注意,您应该只removeAttribute()在 DOM 元素上调用该方法。如果需要disabled从元素集合中删除属性,则必须遍历集合并调用每个单独元素的方法。

这是下一个示例的 HTML。

index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
  </head>

  <body>
    <button disabled class="btn">Button</button>
    <button disabled class="btn">Button</button>
    <button disabled class="btn">Button</button>

    <script src="index.js"></script>
  </body>
</html>

这是相关的 JavaScript 代码。

index.js
const buttons = document.querySelectorAll('.btn');

for (const button of buttons) {
  // ✅ Remove disabled attribute from button
  button.removeAttribute('disabled');
}

我们使用该document.querySelectorAll方法选择所有具有类的元素btn

我们使用for...of循环遍历集合并 disabled从每个元素中删除属性。

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐