Is there a JavaScript solution to generating a “table of contents” for a page?

后端 未结 12 1715
广开言路
广开言路 2020-12-12 17:21

I have headers in

through
tags. Is there a way that I can use JavaScript to generate a table of contents for the contents tha

12条回答
  •  無奈伤痛
    2020-12-12 18:11

    I've modified the function in AtesGoral's accepted answer to output correctly nested lists and valid HTML5.

    Just add the code below to your scripts and call TableOfContents(container, output); on load, where container is the class or id of your content element and output is the class or id of the TOC element. Default values are '#contents' and '#toc', respectively.

    See http://codepen.io/aufmkolk/pen/RWKLzr for a working demo.

    function TableOfContents(container, output) {
    var toc = "";
    var level = 0;
    var container = document.querySelector(container) || document.querySelector('#contents');
    var output = output || '#toc';
    
    container.innerHTML =
        container.innerHTML.replace(
            /([^<]+)<\/h([\d])>/gi,
            function (str, openLevel, titleText, closeLevel) {
                if (openLevel != closeLevel) {
                    return str;
                }
    
                if (openLevel > level) {
                    toc += (new Array(openLevel - level + 1)).join('
      '); } else if (openLevel < level) { toc += (new Array(level - openLevel + 1)).join('
    '); } else { toc += (new Array(level+ 1)).join('
  • '); } level = parseInt(openLevel); var anchor = titleText.replace(/ /g, "_"); toc += '
  • ' + titleText + ''; return '' + titleText + ''; } ); if (level) { toc += (new Array(level + 1)).join('
'); } document.querySelector(output).innerHTML += toc; };

提交回复
热议问题