要删除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 代码。
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
方法。
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 代码。
const buttons = document.querySelectorAll('.btn');
for (const button of buttons) {
// ✅ Remove disabled attribute from button
button.removeAttribute('disabled');
}
我们使用该document.querySelectorAll
方法选择所有具有类的元素btn
。
我们使用for...of
循环遍历集合并 disabled
从每个元素中删除属性。