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

在已预设h3标签ID的页面中实现自动生成目录的JS问题

已有预设ID的h3自动生成目录代码修复

原代码问题梳理

  • 变量作用域问题:headers、name仅在$('h3').each()循环内部声明,每次循环会覆盖原有值,循环结束后外部无法访问所有h3的id和文本集合
  • 执行顺序错误:toc.appendChild(tocList)执行时tocList还未初始化,创建ul节点的代码放在了追加操作之后
  • 赋值逻辑错误:a标签的href属性应该拼接对应h3的id值,原代码错误使用了文本内容,遍历逻辑混乱
  • 额外HTML结构问题:页面中h3的闭合标签误写为</h1>,建议修正避免渲染异常

修复后可直接使用的代码

JS代码

$(document).ready(function() {
  setTimeout(() => {
    // 获取ToC容器
    const toc = document.getElementById("ToC");
    // 添加目录标题
    const tocHeader = document.createElement("h2");
    tocHeader.innerText = "目录";
    toc.appendChild(tocHeader);
    // 创建目录列表容器
    const tocList = document.createElement("ul");

    // 遍历所有h3标签直接生成目录项
    $('h3').each(function() {
      const headingId = $(this).attr('id');
      const headingText = $(this).text();
      // 仅为设置了有效id的h3生成目录项
      if(headingId) {
        const tocListItem = document.createElement("li");
        const tocEntry = document.createElement("a");
        tocEntry.setAttribute("href", `#${headingId}`);
        tocEntry.innerText = headingText;
        tocListItem.appendChild(tocEntry);
        tocList.appendChild(tocListItem);
      }
    });

    // 把生成好的列表追加到ToC容器
    toc.appendChild(tocList);
  }, 1000);
});

修正后的页面结构代码

<body>
<div id="ToC"></div>
<div>
    <h3 id="this-is-heading-1">First Heading</h3>
    <p>
        This is paragrah 1
    </p>
    <h3 id="another-heading">Second Section</h3>
    <p>
        This is some words
    </p>
    <h3 id="last-heading">And Finally</h3>
    <p>
        Some more verbiage
    </p>
</div>
</body>

如果你页面的1秒延迟是原有逻辑保留,若页面没有异步加载内容的话可以直接删掉外层的setTimeout包装。

内容的提问来源于stack exchange,提问作者digerati

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.13 13:09:03