最近搜索


没有最近搜索

Christian Espinosa's Avatar

Christian Espinosa

已加入2024年8月20日

·

最后活动2024年8月20日

关注

0

关注者

0

活动总数

2

投票

0

订阅

1

活动概览

的最新活动 Christian Espinosa

Christian Espinosa 进行了评论,

社区评论 Discussion - Tips and best practices from the community

I wanted to contribute to this and provide an up to date version of the original js code without the fragility of regex, onload and var.

document.addEventListener('DOMContentLoaded', function() {
  const tocContainer = document.getElementById('toc');
  const contentContainer = document.getElementById('contents');

  function generateTableOfContents() {
    const headings = contentContainer.querySelectorAll('h1, h2, h3, h4, h5, h6');
    let currentLevel = 0;
    let tableOfContents = '';

    headings.forEach((heading) => {
      const headingLevel = parseInt(heading.tagName.charAt(1));
      const headingText = heading.textContent.trim();
      const headingId = headingText.replace(/\s/g, '_');

      heading.id = headingId;

      if (headingLevel > currentLevel) {
        tableOfContents += '
    '; } else if (headingLevel < currentLevel) { tableOfContents += '
'.repeat(currentLevel - headingLevel); } tableOfContents += `
  • ${headingText}
  • `; currentLevel = headingLevel; }); if (currentLevel > 0) { tableOfContents += ''.repeat(currentLevel); } tocContainer.innerHTML = tableOfContents; } generateTableOfContents(); });

     

    Best,

    Christian

    查看评论 · 已于 2024年8月20日 发布 · Christian Espinosa

    0

    关注者

    0

    投票

    0

    评论