原生JS如何为动态创建的链接添加无值data-scroll-spy属性?
解决方案
要生成无值的data-scroll-spy属性,你只需要调整设置属性的方式,以下两种方法都可以实现需求:
方法1:使用setAttribute传入空字符串
将setAttribute('data-scroll-spy', true)替换为传入空字符串作为属性值,浏览器会自动渲染成无值的属性形式:
$sections.forEach(({ id, firstElementChild: { textContent } }) => { const link = document.createElement('a'); link.classList.add('link'); link.setAttribute('href', `#${id}`); link.setAttribute('data-scroll-spy', ''); // 传入空字符串 link.textContent = textContent; fragment.appendChild(link); });
方法2:使用dataset属性
利用DOM元素的dataset接口,将对应的驼峰命名属性设为空字符串,它会自动转换为短横线分隔的data属性:
$sections.forEach(({ id, firstElementChild: { textContent } }) => { const link = document.createElement('a'); link.classList.add('link'); link.setAttribute('href', `#${id}`); link.dataset.scrollSpy = ''; // 驼峰scrollSpy对应data-scroll-spy link.textContent = textContent; fragment.appendChild(link); });
原理说明
HTML标准中,无值属性本质等价于属性值为空字符串。当你用setAttribute传入true时,浏览器会将其作为字符串值渲染,得到data-scroll-spy="true";而传入空字符串时,浏览器会简化为无值的data-scroll-spy形式,符合你的预期结构。
内容的提问来源于stack exchange,提问作者Facundo
相关产品推荐
相关产品推荐

