如何使用颜色数组依次更改一组相同元素中每个元素的颜色

how to change color for each element in a group of identical elements in sequence with a color array

each() 方法是否能够在元素的每个实例上递增? 此外,如何使每个元素获得与数组对应的背景颜色,$('colorbox')[0] 获得 'yellow',$('colorbox')[ 1] 获得 'blue'..等。我无法使用 $('.colorbox')[k].css() 或 document.querySelector('.colorbox')[k].[=20= 访问 属性 ]="";因为我得到一个错误。帮助将不胜感激。

let test = ['yellow', 'blue', 'purple', 'orange', 'red', 'green'];
$('.colorbox').each(function () {
    let k = 0;
    $(this).css("background-color", `${test[k]}`);
    k++;
    })
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>HTML 5 Boilerplate</title>
    <script src="https://code.jquery.com/jquery-3.6.0.js" integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk=" crossorigin="anonymous"></script>
    <link rel="stylesheet" href="styles.css">
  </head>
  <body>
    <div class="container">
        <div class="container-box">
            <div class="colorbox"></div>
            <div class="colorbox"></div>
            <div class="colorbox"></div> 
            <div class="colorbox"></div>
            <div class="colorbox"></div>
            <div class="colorbox"></div>
        </div>
    </div>
    <script src="script.js"></script>
  </body>
</html>
.colorbox {
    display: flex;
    height: 200px;
    width: 200px;
    border: 1px solid black;
    box-sizing: border-box;
    transform: rotateY(180deg);
    transform-style: preserve-3d;
    transition: transform 0.3s ease;
}

你很亲近!每次循环迭代时都会重置 k,因此只需将 let k = 0 放在 .each() 之外。但比使用自己的计数器更好的是,使用通过 each 方法获得的内部索引,如下所示:

let test = ['yellow', 'blue', 'purple', 'orange', 'red', 'green'];
$('.colorbox').each(function (index) {
  $(this).css("background-color", `${test[index]}`);
})

您提到使用 querySelector,您是对的,您绝对不需要 jquery:

const boxes = document.querySelectorAll('.colorbox')
boxes.forEach((box, i) => box.style.backgroundColor=test[i])

这是一个片段:

let test = ['yellow', 'blue', 'purple', 'orange', 'red', 'green'];
/*
$('.colorbox').each(function (index) {
  $(this).css("background-color", `${test[index]}`);
})
*/

const boxes = document.querySelectorAll('.colorbox')
boxes.forEach((box, i) => box.style.backgroundColor = test[i])
.colorbox {
  display: flex;
  height: 200px;
  width: 200px;
  border: 1px solid black;
  box-sizing: border-box;
  transform: rotateY(180deg);
  transform-style: preserve-3d;
  transition: transform 0.3s ease;
}
<div class="container">
  <div class="container-box">
    <div class="colorbox"></div>
    <div class="colorbox"></div>
    <div class="colorbox"></div>
    <div class="colorbox"></div>
    <div class="colorbox"></div>
    <div class="colorbox"></div>
  </div>
</div>