遍历它们DOM

Traversing through them DOM

我在尝试执行以下操作时遇到问题: 当我按下按钮(第一次)时,我希望它到 select 第一个框然后将背景更改为灰色,当按下按钮时,我希望它跳到下一个框并更改那个方框变成灰色。请帮忙!


    const boxes = document.querySelector('#boxes');
    const button = document.querySelector('button');

    button.addEventListener('click', () => {
        let firstChild = boxes.firstElementChild;
        for (let i = 0; i < boxes.length; i++) {
            firstChild.nextElementSibling.style.backgroundColor = 'grey';
        }
    })
    body {
        background: rgb(78, 78, 78);
    }

    .boxes {
        height: 600px;
        width: 380px;
        background: rgb(236, 236, 236);
        border-radius: 20px;
    }

    .box {
        height: 100px;
        background: rgb(26, 149, 187);
    }
    <!doctype html>
    <html lang="en">

    <head>
        <!-- Required meta tags -->
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

        <!-- Bootstrap CSS -->
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
        <!-- My CSS -->
        <link rel="stylesheet" href="main.css">

        <title>Hello, world!</title>
    </head>

    <body>
        <div class="container boxes mt-5">
            <h1 class="text-center mb-4">App.js</h1>
            <div id='boxes' class="row justify-content-around">
                <div class="col-3 box "></div>
                <div class="col-3 box "></div>
                <div class="col-3 box "></div>
            </div>
            <div class="row mt-4 justify-content-around">
                <div class="col-3 box "></div>
                <div class="col-3 box "></div>
                <div class="col-3 box "></div>
            </div>
            <div class="container text-center mt-4">
                <button id="button" type="button" class="btn btn-warning">Submit</button>
            </div>
        </div>
</body>
</html>

这是一种使用闭包的方法:

const boxes = document.querySelector('#boxes');
const button = document.querySelector('button');

const createListener = () => {
  let counter = 0
  return () => {
    boxes.children[counter % 
boxes.children.length].style.backgroundColor = 'gray'
    counter++
  }
}

button.addEventListener('click', createListener())

我没有测试过,但应该可以。如果您不明白发生了什么,请研究闭包。会很有用的。