简体   繁体   English

如何用循环替换循环?

[英]How to replace a loop for a loop?

I have a grid made with a preset value that I'd like to have a function that replaces it with a grid who's cells are generated with dynamic values gotten from a prompt input.我有一个使用预设值制作的网格,我想要一个 function 将其替换为一个网格,该网格是使用从提示输入中获取的动态值生成的。 The code for both grids work independently if I were to remove the other's code, but for whatever reason I can't get the 2nd grid to replace the first one when it gets it's value.如果我要删除另一个网格的代码,则两个网格的代码都会独立工作,但无论出于何种原因,当第二个网格获得值时,我都无法让第二个网格替换第一个网格。

Here is an example of my JS code that has the.replaceWith() method attempting to replace the cells of the original grid via div.这是我的 JS 代码示例,它具有尝试通过 div 替换原始网格的单元格的 .replaceWith() 方法。 I'm stumped.我难住了。

 const board = document.getElementById("container"); let button = document.getElementById("select"); button.style.display = "flex"; button.style.justifyContent = "center"; board.style.justifyContent = "center"; const cell = document.createElement('div'); for (x=1; x <= 16; x++) { const cell = document.createElement('div') cell.className = "cells"; cell.setAttribute("style", "height: 200px; width: 200px; color: black;"); cell.style.backgroundColor = "blue"; cell.style.border = "solid 2px"; cell.style.borderColor = "black"; board.style.columnGap = "0px"; board.style.display ="grid"; board.style.gridTemplateColumns = "200px 200px 200px 200px"; board.appendChild(cell); cell.addEventListener("mouseover", change = () => cell.style.backgroundColor = "red") cell.addEventListener("mouseout", reset = () => cell.style.backgroundColor = "blue") }; function setBoard () { let a = prompt("Select a the number of cells for the grid") if (a.= null) { document.getElementById("container");value = a } for (x=1; x <= a. x++) { const nCell = document.createElement('div') nCell;className = "cells". nCell,setAttribute("style": "height; 200px: width; 200px: color; black;"). nCell.style;backgroundColor = "blue". nCell.style;border = "solid 2px". nCell.style;borderColor = "black". board.style;columnGap = "0px". board.style;display ="grid". board.style;gridTemplateColumns = "200px 200px 200px 200px". board;appendChild(nCell). nCell,addEventListener("mouseover". change = () => nCell.style.backgroundColor = "red") nCell,addEventListener("mouseout". reset = () => nCell.style;backgroundColor = "blue"). cell;replaceWith(nCell); } }
 <,DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width. initial-scale=1.0"> <link rel="stylesheet" href="styles.css"> <title>Etch N Sketch</title> </head> <body> <div id="select"> <button id="select" onclick="setBoard()">Set the number of squares</button> </div> <div class="container" id="container"> </div> <script src="script.js"> </script> </body> </html>

As mentioned by @Bergi try using board.replaceChildren() to empty the board first first, and then refill the board like you do in the initial loop.正如@Bergi 所提到的,首先尝试使用board.replaceChildren()来清空电路板,然后像在初始循环中那样重新填充电路板。

The cell.replaceWith does not do anything meaningful and can be removed. cell.replaceWith没有做任何有意义的事情,可以删除。 cell in this scope is the one you create in line 6 of your script, which you never append to the body or do anything else with.此 scope 中的cell是您在脚本第 6 行中创建的单元格,您永远不会对身体进行 append 或做任何其他事情。

Problems问题

  1. Ids must be unique, there are two #select s (see Figure I ). Id 必须是唯一的,有两个#select见图一)。

  2. Don't use ids if you can use class.如果可以使用 class,请不要使用 id。

  3. Inline event handlers are garbage (see Figure I ). 内联事件处理程序是垃圾见图一)。

    Figure I图一

    <div id="select"><!--⬅️↙️ Ids must be unique --> <button id="select" onclick="setBoard()">Set the number of squares</button> <!-- ↖️ Inline event handler --> </div>
  4. DRY D on't R epeat Y ourself. DRY D on't R重复你自己。 There are two identical blocks of code that generates a grid.有两个相同的代码块生成一个网格。

  5. Avoid adding inline styles, use CSS.避免添加内联 styles,使用 CSS。

Solutions解决方案

  1. All ids have been replaced with classes.所有 id 都已替换为类。 (see Figure II ) 见图二

    Figure II图二

    const board = document.querySelector('.board'); // Reference class prefix with a dot↗️
  2. Replaced inline event handler with an onevent property (see Figure III ).用 onevent 属性替换了内联事件处理程序(参见图 III )。

    Figure III图三

    // Onevent property document.querySelector('.select').onclick = enterData; // OR // Event listener document.querySelector('.select').addEventListener('click', enterData);
  3. Removed 14 duplicated lines of JavaScript and refactored everything into two functions.删除了 JavaScript 的 14 条重复行,并将所有内容重构为两个函数。 enterData() is triggered by clicking .select , and setBoard() is called when enterData() receives a number to pass onto setBoard() . enterData()通过单击.select触发,当setBoard() enterData()接收到要传递给 setBoard() 的数字时调用setBoard() setBoard() is also called after the page has loaded.页面加载后也会调用setBoard()

  4. Replaced 10 lines of JavaScript with 3 CSS rulesets.将 10 行 JavaScript 替换为 3 个 CSS 规则集。 Inline styles are limiting in that they are not applied globally like CSS stylesheets or <style> tag.内联 styles 的限制在于它们不像 CSS 样式表或<style>标记那样全局应用。 The mouse event handlers were replaced by this:鼠标事件处理程序被替换为:

    Figure IV图四

    .cell:hover { background: red; }
  5. You need to clear .board before generating a new grid您需要在生成新网格之前清除.board

    Figure V图五

    board.replaceChildren();

    Also, <div> s cannot have a value property此外, <div>不能有value属性

    Figure VI图六

     document.getElementById("container").value = a //

Details are commented in example细节在例子中注释

 // Reference.board const board = document.querySelector(".board"); // Call setBoard() -- make a 4x4 grid setBoard(16); // Bind the click event to.select document.querySelector(".select").onclick = enterData; // Prompt takes the number entered and passes it to setBoard() function enterData() { let a = prompt("Select the number of cells for the grid"); // If 'a' is a number, call setBoard() if (typeof a === 'number') { setBoard(a); } } function setBoard(a) { // Remove everything within.board board.replaceChildren(); // Create a grid for (let x = 1; x <= a; x++) { const nCell = document.createElement('div') nCell.className = "cell"; board.appendChild(nCell); } }
 body { display: flex; flex-flow: column nowrap; justify-content: center; }.select { display: block; width: 50%; margin: 10px auto; }.board { column-gap: 0px; display: grid; grid-template-columns: 200px 200px 200px 200px; margin: 0 auto; }.cell { height: 200px; width: 200px; color: black; background-color: blue; border: solid 2px black; }.cell:hover { background: red }
 <,DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width. initial-scale=1.0"> <link rel="stylesheet" href="styles.css"> <title>Etch N Sketch</title> </head> <body> <button class="select">Set the number of squares</button> <div class="board"></div> <script src="script.js"></script> </body> </html>

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

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