Javascript 基于html结构构建sidenav菜单
我正在尝试为我的Django项目构建一个文档模板,并提供一些简单的导航。HTML的一般结构如下所示:Javascript 基于html结构构建sidenav菜单,javascript,html,jquery,sidebar,Javascript,Html,Jquery,Sidebar,我正在尝试为我的Django项目构建一个文档模板,并提供一些简单的导航。HTML的一般结构如下所示: div.page-container#overview h3.page-header div h4.section-title div.section-wrapper h5.section-subtitle div.page-container#documentation h3.page-header div h4
div.page-container#overview
h3.page-header
div
h4.section-title
div.section-wrapper
h5.section-subtitle
div.page-container#documentation
h3.page-header
div
h4.section-title
div.section-wrapper
h5.section-subtitle
...
根据生成的HTML,我想要一个侧导航,它与页面上的标题结构相同。这就是我想要的:
HTML
-----------------
div.page-container#overview
h3.page-header="Overview" -----------------|
div |
h4.section-title="Introduction" --------|
div.section-wrapper |
h5.section-subtitle="System" -------|
<p>....</p> |
h5.section-subtitle="User" ---------|
<p>....</p> |
|
SideBar |
----------------- |
Overview <----------------------------|
Introduction <----------------------------|
System <-------------------------------|
User <----------------------------------|
Documentation |
...
...
HTML
-----------------
div.page-container#概述
h3.页眉=“概述”-----------------|
div|
h4.章节标题=“引言”--------|
分区包装器|
h5.章节副标题=“系统”-------|
..|
h5.章节副标题=“用户”---------|
..|
|
边栏|
----------------- |
概述您需要将值放入
标记中以生成该结构。目前,您的代码中只有一个页眉
&节标题
,因此不需要在那里使用循环,只需将其用于节副标题
。然后,无论何时添加新元素,都将它们放入li
标记中
演示代码:
var-htmls=”“//申报
$('.page container')。每个(函数(){
var容器=$(此);
//获取页眉并放入ul>`li`
htmls+=``
//将章节标题放入li>ul>li中
htmls+=``
//循环浏览字幕并放入ul>li>ul>li>ul>li
$(容器)。查找('.section subtitle')。每个(函数(){
htmls+=``
});
//关闭所有标签
htmls+=`
`
})
$(“#侧边栏树”).html(htmls)//添加内部侧边栏。
.page容器{
显示:无
}
概述
介绍
系统
使用者
文档
Sss
Soemthings
soemthings1
function buildSideNav() {
$('.page-container').each(function() {
var container = $(this);
$(container).find('.page-header').each(function() {
$('#sidebar-tree').append(`<a href="#${$(this).attr('id')}">${$(this).text()}</a>`);
$(container).find('.section-title').each(function() {
$('#sidebar-tree').append(`<a class="ml-2" href="#${$(this).attr('id')}">${$(this).text()}</a>`);
$(container).find('.section-subtitle').each(function() {
$('#sidebar-tree').append(`<a class="ml-4" href="#${$(this).attr('id')}">${$(this).text()}</a>`);
});
});
});
})
}