如何用jQuery生成带层级数字的目录?
问题背景
我有如下标题结构:
<h2>Red Fruits</h2> <h3>Apple</h3> <h3>Raspberry</h3> <h2>Orange Fruits</h2> <h3>Orange</h3> <h3>Tangerine</h3> <h2>Vegetables Which Are Actually Fruits</h2> <h3>Tomato</h3> <h3>Eggplant</h3>
当前脚本生成的目录效果:
1. Red Fruits 2. Apple 3. Raspberry 4. Orange Fruits 5. Orange 6. Tangerine 7. Vegetables Which Are Actually Fruits 8. Tomato 9. Eggplant
期望实现的层级数字目录:
1. Red Fruits 1.1 Apple 1.2 Raspberry 2. Orange Fruits 2.1 Orange 2.2 Tangerine 3. Vegetables Which Are Actually Fruits 3.1 Tomato 3.2 Eggplant
以下是需要修改的jQuery代码:
(function($){ function tableContentPost(){ var tocList = $('#toc-list'); $('.page-content').find('h2, h3').each(function(index) { var heading = $(this); var title = heading.text(); var id = 'heading' + index; // Assign an ID to the heading if it doesn't have one if (!heading.attr('id')) { heading.attr('id', id); } else { id = heading.attr('id'); } var listItem = $('<li></li>').html('<a href="#' + id + '">' + title + '</a>'); if (heading.is('h3')) { listItem.addClass('sub-item'); } tocList.append(listItem); }); } $(document).ready(function() { tableContentPost(); }); })( jQuery );
修改方案
要实现层级编号,需要新增两个计数器分别跟踪一级标题(h2)和二级标题(h3)的序号,具体修改如下:
1. 新增计数器变量
在tableContentPost函数开头添加两个计数器,用于记录层级序号:
var h2Counter = 0; var h3Counter = 0;
2. 遍历标题时更新计数器并生成编号
根据标题类型(h2/h3)更新计数器,同时把层级编号插入到列表项内容前:
- 遇到h2时,递增一级计数器,重置二级计数器
- 遇到h3时,递增二级计数器,生成
一级序号.二级序号的格式
修改后的完整代码
(function($){ function tableContentPost(){ var tocList = $('#toc-list'); // 新增层级计数器 var h2Counter = 0; var h3Counter = 0; $('.page-content').find('h2, h3').each(function() { var heading = $(this); var title = heading.text(); // 优化ID生成逻辑,避免重复 var id = heading.attr('id') || 'heading_' + Date.now() + Math.floor(Math.random()*1000); // 为无ID的标题赋值ID if (!heading.attr('id')) { heading.attr('id', id); } var listItem; if (heading.is('h2')) { h2Counter++; h3Counter = 0; // 重置二级计数器 listItem = $('<li></li>').html('<a href="#' + id + '">' + h2Counter + '. ' + title + '</a>'); } else { h3Counter++; listItem = $('<li></li>').html('<a href="#' + id + '">' + h2Counter + '.' + h3Counter + ' ' + title + '</a>'); listItem.addClass('sub-item'); } tocList.append(listItem); }); } $(document).ready(function() { tableContentPost(); }); })( jQuery );
额外说明
- 优化了ID生成逻辑,用时间戳+随机数替代原有的index,避免页面已有相同ID导致的跳转错误
- 层级计数器的重置逻辑确保每个一级标题下的二级标题都从1开始编号
内容的提问来源于stack exchange,提问作者Vladimir
相关产品推荐
相关产品推荐

