You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用原生JavaScript为PHP生成的容器设置循环重复的Class

原生JS实现循环替换HTML容器类名(test1/test2/test3循环)

现有代码

CSS

.test {
  background: red;
}
.test1 {
  background: blue;
}
.test2 {
  background: green;
}
.test3 {
  background: yellow;
}

HTML

<div class="test">This container must have class="test1"</div>
<div class="test">This container must have class="test2"</div>
<div class="test">This container must have class="test3"</div>
<div class="test">From here the function need repeat so this container must have class="test1"</div>
<div class="test">This container must have class="test2"</div>
<div class="test">This container must have class="test3"</div>

解决方案代码

// 获取所有带test类的容器
const containers = document.querySelectorAll('.test');

// 遍历每个容器,替换类名
containers.forEach((item, idx) => {
  // 通过取模实现1/2/3循环
  const classNum = (idx % 3) + 1;
  // 移除旧类,添加新类
  item.classList.remove('test');
  item.classList.add(`test${classNum}`);
});

代码说明

  • document.querySelectorAll('.test'):抓取页面中所有带有test类的元素,得到一个可遍历的元素集合。
  • forEach遍历:逐个处理每个元素,item是当前处理的DOM节点,idx是它的序号(从0开始)。
  • 循环逻辑:idx % 3会得到0、1、2的循环结果,加1后就对应1、2、3,刚好匹配需要的类名后缀。
  • classList操作:用remove删掉原来的test类,再用add添加上新的testX类,避免样式叠加冲突。

内容的提问来源于stack exchange,提问作者Eliseo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 19:03:12