
在 javascript 中为 dom 元素添加属性而不设置值
在 JavaScript 中,使用 setAttribute() 方法为 DOM 元素添加属性值是很常见的。但是,如果希望将属性添加到元素而不赋予它值,怎么办?
<p>这是期望得到的效果</p>
<pre><code><body>
<div primary></div>
</body></code></pre>
<p>但是<code>setAttribute('key', 'val')</code>不支持这样的写法?</p>
<pre><code>const element = document.createElement('div');
// element.setAttribute("primary"); // 这个方法只能传属性和值
document.body.append(element)</code></pre>
为了解决这个问题,可以使用 `createAttribute()` 方法创建一个没有值的属性,然后使用 `setAttributeNode()` 方法将它附加到元素上:
<p>试试这个</p>
<pre>const attr = document.createAttribute('primary');
const ele = document.createElement('div');
ele.setAttributeNode(attr);
document.body.append(ele);</pre>
以上就是如何在 JavaScript 中为 DOM 元素添加属性而不设置值?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号