jQuery基于div类名实现自动编号 忽略隐藏类元素自动排序
动态生成可见元素连续序号实现方案
需求说明
- 为每一行元素自动分配递增序号
- 带有
tc-hidden类的隐藏元素不参与排序,直接跳过 - 所有可见元素的序号需要保持连续,不出现断号
原有实现问题
原有方案通过CSS硬编码每个类名对应序号的方式实现,序号和元素类名强绑定,不会感知元素的显隐状态:
:before{ display:block; margin-top:10px; font: inherit; } .tc-hidden{ display:none; } /* 硬编码绑定类名的固定序号,无法动态适配显隐变化 */ .tc1 h3.tm-section-label:before { content: "1"; } .tc2 h3.tm-section-label:before { content: "2"; } .tc3 h3.tm-section-label:before { content: "3"; } .tc4 h3.tm-section-label:before { content: "4"; }
对应HTML结构如下:
<div class="tc-cell tc1"> <h3 class="tm-section-label"></h3> </div> <div class="tc-cell tc2 tc-hidden"> <h3 class="tm-section-label"></h3> </div> <div class="tc-cell tc3 tc-hidden"> <h3 class="tm-section-label"></h3> </div> <div class="tc-cell tc4"> <h3 class="tm-section-label"></h3> </div>
该实现下,即使tc2、tc3被隐藏,tc4对应的序号依然是硬编码的4,不符合预期的连续序号逻辑(tc4应为2)。
正确实现代码
第一步:调整CSS
删除所有硬编码序号的规则,改为通过CSS变量读取动态生成的序号:
:before{ display:block; margin-top:10px; font: inherit; } .tc-hidden{ display:none; } h3.tm-section-label:before { content: var(--section-index); }
第二步:编写jQuery动态编号逻辑
// 序号更新方法,页面初始化、元素显隐/增删后都可调用 function refreshSectionIndex() { // 筛选所有不带tc-hidden类的可见行,按DOM顺序遍历 $('.tc-cell:not(.tc-hidden)').each(function(seq) { // 序号从1开始,给当前行的标签设置CSS变量 $(this).find('.tm-section-label').css('--section-index', seq + 1); }); } // 页面DOM加载完成后首次执行编号 $(function() { refreshSectionIndex(); });
效果说明
执行上述代码后,示例中tc1序号为1,被隐藏的tc2、tc3直接跳过,tc4序号自动计算为2,完全符合连续序号的要求。后续如果有切换元素显隐、新增/删除行的操作,只要操作完成后调用refreshSectionIndex()即可重新计算全量可见元素的序号,不会出现错号、断号问题。
内容的提问来源于stack exchange,提问作者yasin
相关产品推荐
相关产品推荐

