You need to enable JavaScript to run this app. 使用jQuery提取指定div的H2/H3生成目录时如何避免div嵌套
优惠活动
大模型
产品
解决方案
定价
更多

使用jQuery提取指定div的H2/H3生成目录时如何避免div嵌套

问题根因

你的嵌套问题是因为代码只创建了H2对应div的起始标签,既没有在遇到下一个H2时闭合上一个div,也没有在循环结束后闭合最后一个div,同时还多写了一段无效的</a>标签,才会导致后续div全部被嵌套进前一个div。

修改后可用的JS代码

$(document).ready(function toc_builder() {
  var children = $("#contents").children('H2, H3');
  var html = "";
  for (var i = 0; i < children.length; i++) {
    $(children[i]).prop('id', 'toc-item-' + i);
    var tagName = $(children[i]).prop('tagName');
    if (tagName == 'H2') {
      // 遇到新H2时先闭合上一个未关闭的div
      if (i !== 0) {
        html += "</div>";
      }
      // 生成新div起始标签,移除多余的无效</a>
      html += "<div class=\"" + $(children[i]).text().trim().replace(/ /g, "_") + "\">";
    } else if (tagName == 'H3') {
      html += "<a class=\"list-group-item\" href=\"#toc-item-" + i + "\">" + $(children[i]).html() + "</a>";
    }
  }
  // 循环结束后补全最后一个div的闭合标签
  if (children.length > 0) {
    html += "</div>";
  }
  $("#toc").html(html);
});

优化说明

  • 单独提取tagName查询逻辑,减少重复DOM操作
  • H2内容取值改用.text().trim(),避免H2内嵌HTML标签、前后带空格导致class命名异常
  • 补全了div闭合逻辑,保证所有H2对应的div都是平级结构
    修改后生成的目录结构完全符合你的预期,对应CSS样式也能正常生效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.08 03:33:03