当编写长篇文章或技术文档时,为了方便读者阅读和快速导航,添加一个目录结构是一种常见的做法。在本文中,我将介绍如何使用JavaScript根据文章中的HTML标签生成一个目录结构。
准备工作
首先,我们需要一个由HTML标签组成的文章。在这个示例中,我们将使用h2-会标签来构建标题层次结构。
<div id="menu">menu</div> <div id="article-content"> <h2>文章目录1</h2> <div>文章内容1文章内容1文章内容1文章内容1</div> <h3>文章目录1-1</h3> <div>章内容1文章内容1文章内容1文章内容1</div> <h3>文章目录1-2</h3> <div>章内容1文章内容1文章内容1文章内容1</div> <h2>文章目录2</h2> <div>章内容1文章内容1文章内容1文章内容1</div> <h3>文章目录2-1</h3> <div>章内容1文章内容1文章内容1文章内容1</div> <h3>文章目录2-2</h3> <div>章内容1文章内容1文章内容1文章内容1</div> <h2>文章目录3</h2> <div>章内容1文章内容1文章内容1文章内容1</div> <h3>文章目录3-1</h3> <div>章内容1文章内容1文章内容1文章内容1</div> </div>
生成目录结构
要生成目录结构,我们可以编辑一个JavaScript函数。以下是一个基本的实现:
function createMenu() {
// 首先获取所有H标签,若页面中有h4,h5,h6则可以添加到参数中
var headList = [...document.querySelectorAll("h1,h2,h3")]; // 将H标签构造成一棵树,就可以明确H标签之间的层级
var root = {
children: []
};
var h = {
node: headList[0],
children: [],
parent: root
};
root.children.push(h);
headList.reduce(function (pre, cur) {
var n = {
node: cur,
children: []
};
while (h.node.localName[1] - n.node.localName[1] !== -1) {
h = h.parent;
if (h === root) {
break;
}
}
n.parent = h;
h.children.push(n);
h = n;
return h;
}); // 给H标签加id
var index = 1;
function createList(list) {
var text = list.reduce(function (pre, cur) {
var childText; // 判断该H标签有没有子层H标签
if (cur.children.length) {
childText = createList(cur.children);
} else {
childText = "";
}
cur.node.id = "header" + index++;
pre += `<li>
<a href="#${cur.node.id}">
${cur.node.innerHTML}
</a>
${childText}
</li>`;
return pre;
}, "");
var text = `<ul> ${text} </ul>`;
return text;
}
var content = createList(root.children);
document.getElementById("menu").innerHTML = content;
}
createMenu();//调用最终效果图
以下是运行代码后的结果文章来源:https://www.toymoban.com/article/696.html
文章来源地址https://www.toymoban.com/article/696.html
到此这篇关于使用 js 根据文章中h标签生成目录结构,生成树状结构的文章就介绍到这了,更多相关内容可以在右上角搜索或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!











