admin管理员组文章数量:1641070
要删除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.jsconst 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 代码。
index.jsconst buttons = document.querySelectorAll('.btn');
for (const button of buttons) {
// ✅ Remove disabled attribute from button
button.removeAttribute('disabled');
}
我们使用该document.querySelectorAll
方法选择所有具有类的元素btn
。
我们使用for...of
循环遍历集合并 disabled
从每个元素中删除属性。
本文标签: 属性JavaScriptdisabled
版权声明:本文标题:使用 JavaScript 删除disabled属性 内容由热心网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:https://www.elefans.com/dongtai/1729316725a1195378.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论