求帮助,Wordpress 添加文章目录到侧边栏遇到的问题:
文章是用构建器构建的,文章容器被多层嵌套..?
<div class="entry-inner">
<div class="sektion-wrapper nb-loc " data-sek-level="location" data-sek-id="before_content" data-sek-is-global-location="false">
<div data-sek-level="section" data-sek-id="__nimble__fdfe8afc5daa" class="sek-section sek-has-modules ">
<div class="sek-container-fluid"><div class="sek-row sek-sektion-inner">
<div data-sek-level="column" data-sek-id="__nimble__a24b01e49d25" class="sek-column sek-col-base sek-col-100 ">
<div class="sek-column-inner "><div data-sek-level="module" data-sek-id="__nimble__376e3143b538" data-sek-module-type="czr_tiny_mce_editor_module" class="sek-module ">
<div class="sek-module-inner">
<p>111</p>
<p>2222</p>
<h2><2333</h2>
<h2>2344</h2>
....
我换成了自己的目录容器(custom_html-7)和文章容器(sek-module-inner),但获取不到构建器构建的内容。
原代码如下
来源:
https://www.rainng.com/js-wordpress-catalog/#h2-2<(忽略)script>
/*
Author: Azure99
WebSite:
https://www.rainng.com/ GitHub:
https://github.com/Azure99 */
let catalogData = getArticleCatalog();
// 自适应文章目录
if (catalogData != null) {
// dynamic-wrapper 换成你的目录容器
let wrapper = document.getElementById('dynamic-wrapper');
wrapper.innerHTML = generateCatalog(catalogData);
}
// 获取本页面的文章目录信息
function getArticleCatalog() {
// entry-inner 换成你使用主题的文章容器
let articleContent = document.getElementsByClassName('entry-inner');
if (articleContent.length !== 1) {
return null;
}
let catalog = [];
let header = {};
let elements = articleContent[0].childNodes;
// 遍历所有元素
for (let i = 0; i < elements.length; i++) {
if (elements[i].nodeName === 'H2') {
// 为二级标题分配 ID 以供锚点跳转,下同
elements[i].id = 'h2-' + catalog.length;
// 记录此二级标题和其所有的三级子标题
header = {
name: elements[i].innerText,
childHeaders: []
};
catalog.push(header);
} else if (elements[i].nodeName === 'H3') {
elements[i].id = 'h2-' + (catalog.length - 1) + '-h3-' + header.childHeaders.length;
// 记录此三级标题到二级标题下
header.childHeaders.push(elements[i].innerText);
}
}
return catalog;
}
// 根据目录信息生成文章目录代码
function generateCatalog(catalogData) {
let catalog = '<div style="text-align: center; margin-top: 10px;">文章目录</div>';
for (let i = 0; i < catalogData.length; i++) {
let target = '#h2-' + i; // 跳转目标
let index = (i + 1) + '. '; // 标题索引
let name = catalogData[i].name; // 标题
catalog += '<a href="' + target + '">' + index + name + '</a><br/>';
for (let i2 = 0; i2 < catalogData[i].childHeaders.length; i2++) {
target = '#h2-' + i + '-h3-' + i2;
index = (i + 1) + '.' + (i2 + 1) + '. ';
name = catalogData[i].childHeaders[i2];
catalog += ' <a href="' + target + '">' + index + name + '</a><br/>'
}
}
return catalog;
}
<(忽略)/script>