You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

原生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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 21:22:18