几天前我需要做一个类似的事情,虽然不是网络控制,但是使用了jQuery。
$(document).ready(buildTableOfContents);
function buildTableOfContents() {
var headers = $('#content').find('h1,h2,h3,h4,h5,h6');
var root, list;
var previousLevel = 1;
var depths = [0, 0, 0, 0, 0, 0];
root = list = $('<ol />');
for (var i = 0; i < headers.length; i++) {
var header = headers.eq(i);
var level = parseInt(header.get(0).nodeName.substring(1));
if (previousLevel > level) {
// Move up the tree
for (var L = level; L < previousLevel; L++) {
list = list.parent().parent();
depths[L] = 0;
}
} else if (previousLevel < level) {
// A sub-item
for (var L = previousLevel; L < level; L++) {
var lastItem = list.children().last();
// Create an empty list item if we're skipping a level (e.g., h1 -> h3)
if (lastItem.length == 0)
lastItem = $('<li />').appendTo(list);
list = $('<ol />').appendTo(lastItem);
}
}
depths[level - 1]++;
// Grab the ID for the anchor
var id = header.attr('id');
if (id == '') {
// If there is no ID, make a random one
id = header.get(0).nodeName + '-' + Math.round(Math.random() * 1e10);
header.attr('id', id);
}
var sectionNumber = depths.slice(0, level).join('.');
list.append(
$('<li />').append(
$('<a />')
.text(sectionNumber + ' '+ header.text())
.attr('href', '#' + id)));
previousLevel = level;
}
$('#table-of-contents').append(root);
}
这将生成一个有序列表并将其附加到
#table-of-contents
有适当的编号(如1.1)。只需要一点CSS就可以隐藏列表的内置编号:
#table-of-contents ol { list-style:none; }