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

如何使用JavaScript更新所有表格偶数行的样式?

表格偶数行背景色设置问题解决办法

你代码失效的原因很简单:document.querySelectorAll()返回的是多个元素组成的NodeList集合,不是单个DOM元素,没法直接通过.style属性批量修改样式,得挨个处理集合里的每一行。

两种可行的JS实现方法

  • 用forEach遍历(现代浏览器支持)
function col() {
  document.querySelectorAll("tr:nth-child(even)").forEach(tr => {
    tr.style.backgroundColor = "#f2f2f2"; // 替换成你需要的颜色
  });
}
  • 传统for循环(兼容旧浏览器)
function col() {
  const evenRows = document.querySelectorAll("tr:nth-child(even)");
  for (let i = 0; i < evenRows.length; i++) {
    evenRows[i].style.backgroundColor = "#f2f2f2";
  }
}

更优方案:直接用CSS

其实没必要用JS来做,用CSS就能直接实现偶数行着色,代码更简洁性能也更好:

tr:nth-child(even) {
  background-color: #f2f2f2;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 22:02:32