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

后端 未结 12 1731
广开言路
广开言路 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条回答
  •  猫巷女王i
    2020-12-12 18:13

    So I had a problem with the answer provided by @Ates Goral and @Hendrik, I use a WYSIWYG which adds some html snippets in the H1-h6 elements like br tags and the rest. So the code breaks and doesn't recognize it as a valid h element since it doesn't match the search pattern. Also some WYSIWYG leave empty h-tags which are not excluded since they have no content. And the various modifications that follows often break with the same problem. A major bug I fixed was that if you had a heading, with the same text it would only reference the first- solutions provided by @Ates Goral and @Hendrik

    I should state that this solution is good if you are generating the table of content from data stored in the database. And I used some of the solutions above and built upon, especially @Ates Goral and @Hendrik

    function TableOfContents(container, output) {
            var txt = "toc-"; 
            var toc = "";
            var start = 0;
            var output = output || '#toc';
    
            var container = document.querySelector(container) || document.querySelector('#contents');
            var c = container.children;
    
            for (var i = 0; i < c.length; i++) {
            var isHeading = c[i].nodeName.match(/^H\d+$/) ;
            if(c[i].nodeName.match(/^H\d+$/)){
                var level = c[i].nodeName.substr(1);
    // get header content regardless of whether it contains a html or not that breaks the reg exp pattern
                var headerText = (c[i].textContent);
    // generate unique ids as tag anchors
                var anchor = txt+i;
    
                var tag = '' + headerText + '';
    
                c[i].innerHTML = tag;
    
                if(headerText){
                    if (level > start) {
                        toc += (new Array(level - start + 1)).join('
      '); } else if (level < start) { toc += (new Array(start - level + 1)).join('
    '); } else { toc += (new Array(start+ 1)).join('
  • '); } start = parseInt(level); toc += '
  • ' + headerText + ''; } } } if (start) { toc += (new Array(start + 1)).join('
'); } document.querySelector(output).innerHTML += toc; } document.addEventListener('DOMContentLoaded', function() { TableOfContents(); } );

提交回复
热议问题