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

使用jQuery循环为6个HTML方块设置对应背景色

用jQuery为方块逐一设置对应背景色的实现方案

没问题,这事儿很容易搞定!咱们可以利用jQuery的.each()方法,结合元素的索引来匹配你的颜色数组,给每个方块精准设置对应的背景色。下面是完整的实现代码:

完整代码示例

<!-- HTML部分 -->
<div id="container">
  <div class="square"></div>
  <div class="square"></div>
  <div class="square"></div>
  <div class="square"></div>
  <div class="square"></div>
  <div class="square"></div>
</div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
// 颜色数组
var color = [ 
  "rgb(255, 0, 0)", 
  "rgb(255, 255, 0)", 
  "rgb(0, 255, 0)", 
  "rgb(0, 255, 255)", 
  "rgb(0, 0, 255)", 
  "rgb(255, 0, 255)" 
];

// DOM加载完成后执行
$(document).ready(function() {
  // 遍历每个.square元素
  $(".square").each(function(index) {
    // 通过索引获取对应颜色,设置背景色
    $(this).css("backgroundColor", color[index]);
    // 可选:给方块添加基础样式让它显示出来
    $(this).css({
      width: "100px",
      height: "100px",
      float: "left",
      margin: "5px"
    });
  });
});
</script>

关键代码说明

  • $(document).ready():确保DOM完全加载后再执行jQuery代码,避免出现找不到元素的问题。
  • $(".square").each(function(index) {...}):遍历所有带square类的元素,index参数是当前元素在集合中的位置(从0开始),刚好和你的颜色数组索引一一对应。
  • $(this).css("backgroundColor", color[index]):把当前方块的背景色设置为颜色数组中对应索引的颜色值。
  • 额外添加的宽高样式是为了让方块能直观显示出来,如果你已经给方块写了样式,可以去掉这部分代码。

内容的提问来源于stack exchange,提问作者Pak Hang Leung

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 08:55:50