Created
September 13, 2018 13:38
-
-
Save akkuman/405ba78b5fae627758d08e340e8b4700 to your computer and use it in GitHub Desktop.
[生成目录遍历所有header.js] 遍历所有的header标签生成导航树 #javascript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Convert item of header array to html in li | |
* @param item An element of header array | |
*/ | |
var itemToHtml = function(item) { | |
return '<a href="#' + item.id + '" id="' + 'menu-'+ item.id + '" >' + item.innerText + '</a>'; | |
}; | |
/** | |
* Generate tree from header array | |
* @param toc_list An array containing header elements | |
* @param p_baseLevel The base level number of the toc you want to display | |
*/ | |
var tocToTree = function(toc_list, p_baseLevel) { | |
let i; | |
let p_toc = []; | |
for (i in toc_list) { | |
let itemLevel = parseInt(toc_list[i].tagName.substring(1)); | |
if (itemLevel >= p_baseLevel) { | |
p_toc.push(toc_list[i]); | |
} | |
} | |
let front = '<li>'; | |
let ending = ['</li>']; | |
let curLevel = p_baseLevel; | |
let toclen = p_toc.length; | |
for (i in p_toc) { | |
let item = p_toc[i]; | |
console.log(item.tagName); | |
let itemLevel = parseInt(item.tagName.substring(1)); | |
if (item.tagName == curLevel) { | |
front += '</li>'; | |
front += '<li>'; | |
front += itemToHtml(item); | |
} else if (itemLevel > curLevel) { | |
// assert(item.level - curLevel == 1) | |
front += '<ul>'; | |
ending.push('</ul>'); | |
front += '<li>'; | |
front += itemToHtml(item); | |
ending.push('</li>'); | |
curLevel = itemLevel; | |
} else { | |
while (itemLevel < curLevel) { | |
let ele = ending.pop(); | |
front += ele; | |
if (ele == '</ul>') { | |
curLevel--; | |
} | |
} | |
front += '</li>'; | |
front += '<li>'; | |
front += itemToHtml(item); | |
} | |
} | |
while (ending.length > 0) { | |
front += ending.pop(); | |
} | |
front = front.replace("<li></li>", ""); | |
front = '<ul>' + front + '</ul>'; | |
return front; | |
}; | |
let headerObjList = $(":header").toArray(); | |
$('.toc').append(tocToTree( headerObjList, 2 )); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment