如何在单击 JS 生成的特定元素时添加颜色

我正在使用 HTML、CSS 和 vanilla JS 创建一个像素艺术制作工具。大部分时间我都创建了 UI,但我无法使用该功能。我试过了:


let cell = document.body.querySelectorAll('.grid-square');

cell.addEventListener('click', function() {

    cell.style.backgroundColor = 'red';

});

但是我的页面“addEventListener”不是一个函数。如何让我的 JS 在 HTML 之后加载,以便我可以让它工作?


紫衣仙女
浏览 141回答 2
2回答

慕姐8265434

let cells = document.body.querySelectorAll('.grid-square'); // querySelectorAll return all elements which have grid-square class.for(let i = 0; i < cells.length; i++){&nbsp; &nbsp; &nbsp; &nbsp; cells[i].addEventListener('click', function(){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; cells[i].style.backgroundColor = "red";&nbsp; &nbsp; });}

月关宝盒

只需 2 个步骤即可使此工作正常进行:querySelectorAll返回一个元素数组,因此您需要遍历它们以将侦听器添加到每个单元格:function setUpCellListeners(){    let cells = document.querySelectorAll('.grid-square');    cells.forEach((cell) => {        cell.addEventListener('click', function() {            cell.style.backgroundColor = 'red';        });   });}您需要在创建单元格后执行此操作。它们是在createGrid函数中创建的,因此我们可以通过在该函数的末尾调用它来实现://function to build the grid based on user inputfunction createGrid(height = 25, width = 25) {    /* code to set up grid.... */    // NOW we can set up our listeners because our grid is created    setUpCellListeners();}工作示例:let canvas = document.querySelector('.canvas');let button = document.querySelector('button');let high;let wide;let color = document.querySelector('.colorChoice').value;function setUpCellListeners(){    let cells = document.querySelectorAll('.grid-square');    cells.forEach((cell) => {       cell.addEventListener('click', function() {           cell.style.backgroundColor = 'red';       });    });}//function to build the grid based on user inputfunction createGrid(height = 25, width = 25) {    canvas.innerHTML = '';    for (let i = 0; i < height; i++) {        let row = document.createElement('div');        row.classList.add('row');        canvas.appendChild(row);        for (let j = 0; j < width; j++) {            let cell = document.createElement('div');            cell.classList.add('grid-square');            row.appendChild(cell);        }    }    setUpCellListeners();}//listens for input of rows and columnsbutton.addEventListener('click', function() {    high = parseInt(document.querySelector('.column-input').value);    wide = parseInt(document.querySelector('.row-input').value);    if (Number.isNaN(high) || Number.isNaN(wide)) {        createGrid();    } else {        createGrid(wide, high);    }});//Default grid built on loadwindow.onload = createGrid(25, 25);.grid-square {    height: 12px;    width: 12px;    border: 1px black solid;}.row {    display: flex;    justify-content: center;}.canvas {    max-height: inherit;    max-width: 75%;}   <!-- Bootstrap CSS -->    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">        <!-- Navbar -->    <nav class="navbar navbar-dark bg-dark">        <span class="navbar-brand mb-0 h1 mx-auto navbar-brand">Pixel Art Maker</span>    </nav>    <!-- Container to put grid in -->    <div class="container shadow p-3 mb-5 bg-white rounded mt-5 main">            <div class="container canvas d-flex-inline">              </div>      <form class="d-flex-inline w-50 mx-auto">        <div class="d-flex">          <div class="form-group w-25 ml-auto mr-2">            <label class="d-block text-center" for="gridRows">Rows</label>            <input type="number" class="form-control row-input" id="gridRows">          </div>          <div class="form-group w-25 mr-auto ml-2">            <label class="d-block text-center" for="gridColumns">Columns</label>            <input type="number" class="form-control column-input" id="gridColumns">          </div>        </div>          </form>        <div class="form-group w-25 mx-auto">          <button type="submit" class="btn btn-primary w-100">Submit</button>        </div>      <form class="d-flex-inline w-50 mx-auto">        <div class="form-group w-25 mx-auto">          <label for="color">Color</label>          <input type="color" class="form-control colorChoice" id="color">        </div>      </form>    </div><!-- Optional JavaScript -->    <!-- jQuery first, then Popper.js, then Bootstrap JS, then local JS -->    <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>    <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script>    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV" crossorigin="anonymous"></script>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript