如何用jQuery或PHP对相同id标签后的item类元素添加wrapAll包裹
方案1:PHP端预处理分组(优先推荐)
直接在后端数据输出前完成分组,无需额外JS处理,性能更高、无DOM渲染闪烁问题,最终输出就是你要的目标结构:
<?php // 第一步:先按标题首字母对数据分组 $groupedList = []; foreach ($forlop as $value) { $firstChar = substr($value->getTitle(), 0, 1); $groupKey = is_numeric($firstChar) ? 'other' : strtolower($firstChar); $groupedList[$groupKey][] = $value; } // 第二步:按分组循环输出结构 foreach ($groupedList as $groupKey => $groupItems) : $showTitle = $groupKey === 'other' ? '0-9' : strtoupper($groupKey); ?> <h3 id="<?php echo $groupKey; ?>"><?php echo $showTitle; ?></h3> <div class="items-add"> <?php foreach ($groupItems as $item) : ?> <div class="item"><?php echo $item->getId(); ?></div> <?php endforeach; ?> </div> <?php endforeach; ?>
方案2:jQuery端实现(前端处理方案)
保留你原有h3去重逻辑,新增包裹容器逻辑即可:
// 原有去重h3逻辑 $('[id]').each(function (i) { $('[id="' + this.id + '"]').slice(1).remove(); }); // 新增同组item包裹逻辑 $('h3').each(function() { // 选中当前h3之后、下一个h3之前的所有.item元素,统一包裹 $(this).nextUntil('h3', '.item').wrapAll('<div class="items-add"></div>'); });
内容的提问来源于stack exchange,提问作者nhungo duc
相关产品推荐
相关产品推荐

