如何通过JavaScript循环生成适配用户新增div的动态导航
动态导航生成解决方案
操作步骤
- 第一步:给所有需要关联导航的div追加类名
gohere,修改后的div结构如下:
<div class="divdiv gohere" id="div_id"> <h3>DIV TITLE</h3> <br> Description <br> <p>Description</p> <hr> </div>
- 第二步:给导航容器ul设置唯一id,方便JS选中操作:
<ul id="nav-list"> <!-- 导航项将自动插入到此处,无需手动写死 --> </ul>
- 第三步:编写JS逻辑实现自动生成导航
// 封装导航生成函数,方便后续新增div后手动调用刷新 function generateNav() { // 获取导航容器 const navList = document.getElementById('nav-list'); // 清空原有导航,避免重复生成 navList.innerHTML = ''; // 获取所有带gohere类的div元素 const targetDivs = document.querySelectorAll('.gohere'); // 遍历所有目标div生成导航项 targetDivs.forEach(div => { // 取div的id作为锚点 const divId = div.id; // 取div内部h3的文本作为导航显示名称 const navText = div.querySelector('h3').innerText; // 生成li元素 const li = document.createElement('li'); // 生成a元素 const a = document.createElement('a'); // 设置锚点链接 a.href = `#${divId}`; // 设置导航显示文本 a.innerText = navText; // 把a插入li,再把li插入导航容器 li.appendChild(a); navList.appendChild(li); }); } // 页面加载完成后自动执行一次生成导航 window.addEventListener('DOMContentLoaded', generateNav);
补充说明
如果后续用户新增了带gohere类的div,只需要调用一次generateNav()即可刷新导航列表,无需修改其他代码。
内容的提问来源于stack exchange,提问作者QeX41
相关产品推荐
相关产品推荐

