當(dāng)編寫長篇文章或技術(shù)文檔時,為了方便讀者閱讀和快速導(dǎo)航,添加一個目錄結(jié)構(gòu)是一種常見的做法。在本文中,我將介紹如何使用JavaScript根據(jù)文章中的HTML標(biāo)簽生成一個目錄結(jié)構(gòu)。
準(zhǔn)備工作
首先,我們需要一個由HTML標(biāo)簽組成的文章。在這個示例中,我們將使用h2-會標(biāo)簽來構(gòu)建標(biāo)題層次結(jié)構(gòu)。
<div id="menu">menu</div> <div id="article-content"> <h2>文章目錄1</h2> <div>文章內(nèi)容1文章內(nèi)容1文章內(nèi)容1文章內(nèi)容1</div> <h3>文章目錄1-1</h3> <div>章內(nèi)容1文章內(nèi)容1文章內(nèi)容1文章內(nèi)容1</div> <h3>文章目錄1-2</h3> <div>章內(nèi)容1文章內(nèi)容1文章內(nèi)容1文章內(nèi)容1</div> <h2>文章目錄2</h2> <div>章內(nèi)容1文章內(nèi)容1文章內(nèi)容1文章內(nèi)容1</div> <h3>文章目錄2-1</h3> <div>章內(nèi)容1文章內(nèi)容1文章內(nèi)容1文章內(nèi)容1</div> <h3>文章目錄2-2</h3> <div>章內(nèi)容1文章內(nèi)容1文章內(nèi)容1文章內(nèi)容1</div> <h2>文章目錄3</h2> <div>章內(nèi)容1文章內(nèi)容1文章內(nèi)容1文章內(nèi)容1</div> <h3>文章目錄3-1</h3> <div>章內(nèi)容1文章內(nèi)容1文章內(nèi)容1文章內(nèi)容1</div> </div>
生成目錄結(jié)構(gòu)
要生成目錄結(jié)構(gòu),我們可以編輯一個JavaScript函數(shù)。以下是一個基本的實現(xiàn):
function createMenu() { // 首先獲取所有H標(biāo)簽,若頁面中有h4,h5,h6則可以添加到參數(shù)中 var headList = [...document.querySelectorAll("h1,h2,h3")]; // 將H標(biāo)簽構(gòu)造成一棵樹,就可以明確H標(biāo)簽之間的層級 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標(biāo)簽加id var index = 1; function createList(list) { var text = list.reduce(function (pre, cur) { var childText; // 判斷該H標(biāo)簽有沒有子層H標(biāo)簽 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();//調(diào)用
最終效果圖
以下是運行代碼后的結(jié)果文章來源:http://www.zghlxwxcb.cn/article/696.html
文章來源地址http://www.zghlxwxcb.cn/article/696.html
到此這篇關(guān)于使用 js 根據(jù)文章中h標(biāo)簽生成目錄結(jié)構(gòu),生成樹狀結(jié)構(gòu)的文章就介紹到這了,更多相關(guān)內(nèi)容可以在右上角搜索或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!