简体   繁体   English

无法通过JavaScript创建的div将eventListener添加到

[英]Unable to add an eventListener to a through JavaScript created div

I am working on an Etch-A-Scetch project. 我正在进行蚀刻蚀刻项目。 I created grid which contains a certain amount of squares of the same size (the user is able to type in the amount of squares which should be displayed). 我创建了一个网格,其中包含一定数量的相同大小的正方形(用户可以键入应显示的正方形数量)。 To create the squares I used CSS grid and a Javascript for loop. 为了创建正方形,我使用了CSS网格和Javascript for loop。 Now I want to add event listeners, which change the background of each Square when moving over it. 现在,我想添加事件侦听器,该事件侦听器在移动每个Square时会更改其背景。 Unfortunately, it always shows errors when I try to add some. 不幸的是,当我尝试添加一些错误时,它总是显示错误。 The current code doesn't show an error, it just doesn't do anything. 当前代码没有显示错误,只是没有执行任何操作。

The method createSquares() should just create and add the amount of squares to the DOM. 方法createSquares()应该只创建正方形并将其添加到DOM中。 The user types in an amount, for example 10, and the displayed squares are 10 in x-direction and 10 in y-direction --> makes 100 squares in total. 用户键入一个数量,例如10,并且显示的正方形在x方向上为10,在y方向上为10->总共形成100个正方形。 After that I want to add an event listener, which changes the background color of the square the user hovers over (the background color should stay changed). 之后,我想添加一个事件侦听器,该事件侦听器将更改用户悬停的正方形的背景颜色(背景颜色应保持更改)。 I am thankful for any help, because I'm really clueless :D 我很感谢您的帮助,因为我真的很笨:

 let squareDiv = document.querySelector('.squareDiv'); let squares = document.getElementById('#squares') let squareAmount = 10; function blackColor() { this.style.backgroundColor = '#000'; this.style.border = '0px'; } function createSquares() { for (i = 0; i < squareAmount * squareAmount; i++) { squares = document.createElement('div'); squares.setAttribute("id", "squares"); // squares.setAttribute("onmouseover", "addEventListener") squares.style.display = 'grid'; squareDiv.style.setProperty('--columns-amount', squareAmount); squareDiv.style.setProperty('--rows-amount', squareAmount); squareDiv.appendChild(squares); } } createSquares(); if (squares) { squares.addEventListener('mouseover', _ => { squares.style.backgroundColor = blackColor; }); } 
 <div class="squareDiv"></div> <div id="squares"></div> 

You likely need something like this 您可能需要这样的东西

I fixed the script, now fix the CSS 我修复了脚本,现在修复了CSS

 let container = document.getElementById("container") let squareAmount = 5; function getRandom() { return '#'+Math.floor(Math.random()*16777215).toString(16); } function colorIt(sq) { sq.style.backgroundColor = document.getElementById("random").checked? getRandom() : '#000'; sq.style.border = '0px'; } function createSquares() { let grid = document.createElement('div'); grid.setAttribute("id","squares") grid.classList.add("grid"); for (i = 0; i < squareAmount * squareAmount; i++) { square = document.createElement('div'); square.classList.add("square"); grid.appendChild(square); } container.innerHTML=""; container.appendChild(grid) } createSquares(); container.addEventListener('mouseover', e => { const target = e.target; if (target.matches(".square")) colorIt(target) } ); 
 .grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(8rem, 1fr)); grid-auto-rows: 1fr; } .grid::before { content: ''; width: 0; padding-bottom: 100%; grid-row: 1 / 1; grid-column: 1 / 1; } .grid > *:first-child { grid-row: 1 / 1; grid-column: 1 / 1; } /* Just to make the grid visible */ .grid > * { background: rgba(0,0,0,0.1); border: 1px white solid; } 
 <label><input type="checkbox" id="random" />Random</label> <div id="container"></div> 

  1. You have already created the element in DOM, please remove this. 您已经在DOM中创建了元素,请删除此元素。
  2. while creating the element using function createSquares assign class instead of ID. 在使用函数createSquares创建元素时,将分配类而不是ID。 Since, you should have only element with one ID. 既然如此,您应该只有一个ID的元素。
  3. Move the addEventListener inside the function after you have created the element. 创建元素后,将addEventListener函数内。

When creating similar html elements with same properties it is better to group them together with class and not id . 当创建具有相同属性的类似html元素时,最好将它们与class而不是id分组在一起。 This is good because it becomes simple to loop these html elements with forEach or other looping methods you may prefer. 这很好,因为使用forEach或您可能更喜欢的其他循环方法来循环这些html元素变得很简单。

 let squareDiv = document.querySelector('.squareDiv'); let squares = document.getElementById('#squares') let squareAmount = 10; function blackColor() { this.style.backgroundColor = '#000'; this.style.border = '0px'; } function createSquares() { for (i = 0; i < squareAmount * squareAmount; i++) { squares = document.createElement('div'); squares.setAttribute("class", "squares"); squares.setAttribute("style", "width: 100px; height: 100px; background: #090; margin-bottom: .3rem;"); // squares.setAttribute("onmouseover", "addEventListener") squares.style.display = 'grid'; squareDiv.style.setProperty('--columns-amount', squareAmount); squareDiv.style.setProperty('--rows-amount', squareAmount); squareDiv.appendChild(squares); } } createSquares(); if (squares) { squares.addEventListener('mouseover', _ => { squares.style.backgroundColor = blackColor; }); } 
 <div class="squareDiv"></div> <div id="squares"></div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM