Skip to content

Instantly share code, notes, and snippets.

@akkuman
Created September 12, 2018 13:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save akkuman/7899a97bf8c92357927333e8788ba56d to your computer and use it in GitHub Desktop.
Save akkuman/7899a97bf8c92357927333e8788ba56d to your computer and use it in GitHub Desktop.
[生成目录.js] 动态生成h2,h3目录 #javascript
let genToc = function() {
let tor_tree = document.createElement('div');
tor_tree.id = 'torTree';
tor_tree.innerHTML += ' <h4 id="anchor-0">导航树</h4>';
$(":header").each(function(index, element) {
let tag_name = $(this)[0].tagName;
let tag_a_html = '';
if (tag_name == 'H2'||tag_name == 'H3') {
let anchor_text = 'anchor-'+(index+1);
$(this).attr('id', anchor_text);
tag_a_html += '<a href="#' + anchor_text + '"><span id="toc-' + anchor_text + '" class="tor' + 'i'.repeat(parseInt(tag_name.substr(-1,1))-1) + '">' + $(this)[0].innerText + '</span><br></a>';
}
tor_tree.innerHTML += tag_a_html;
});
$('.toc').append(tor_tree.outerHTML);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment