简体   繁体   English

我的嵌套 function 没有按我的意愿运行

[英]My nested function isn't operating as I would like

My makeRows function isn't working as I would expect, I'm not sure if I'm going about this the right way.我的makeRows function 没有像我预期的那样工作,我不确定我是否以正确的方式解决这个问题。 When I press "clear all" the prompt runs to make new rows and columns but the mouseOver class isn't being added back to the whole grid, only the bottom part.当我按“全部清除”时,提示运行以创建新的行和列,但是mouseOver class 没有被添加回整个网格,只有底部。

 const container = document.getElementById("container"); function makeRows(rows, cols) { container.style.setProperty("--grid-rows", rows); container.style.setProperty("--grid-cols", cols); for (c = 0; c < rows * cols; c++) { const cell = document.createElement("div"); container.appendChild(cell).className = "grid-item mouseOver"; } } window.onload = makeRows(16, 16); const btn = document.querySelector("button"); const div = container.getElementsByTagName("div"); function reset() { [].forEach.call(div, function (el) { el.classList.remove("mouseOver"); }); let num = prompt("How many rows and cols?"); makeRows(num, num); } btn.addEventListener("click", reset);
 :root { --grid-cols: 1; --grid-rows: 1; } #container { display: grid; grid-template-rows: repeat(var(--grid-rows), 1fr); grid-template-columns: repeat(var(--grid-cols), 1fr); }.grid-item { padding: 1rem; border: 1px solid #ddd; text-align: center; }.mouseOver { transition: 0s 10s; }.mouseOver:hover { background-color: aqua; transition: 0s; } #btn { max-width: 100%; width: 100%; padding: 1rem; margin-bottom: 1rem; margin-top: 1rem; }
 <,DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width. initial-scale=1.0" /> <title>Etch-A-Sketch</title> <link rel="stylesheet" href="etch.css" /> </head> <header> <button id="btn">Clear All</button> </header> <body> <div id="container"></div> </body> <footer> <script src="etch-script.js"></script> </footer> </html>

To remove all items with class grid-item use this iteration in your reset function:要删除所有具有 class grid-item ,请在重置 function 中使用此迭代:

function reset() {
  document.querySelectorAll('.grid-item').forEach(e => e.parentNode.removeChild(e));
  let num = prompt("How many rows and cols?");
  makeRows(num, num);
}

This selects all elements with class grid-item and for each found div it selects its parent node and removes itself from it.这将选择所有具有 class 网格项的元素,并为每个找到的 div 选择其父节点并从中删除自身。

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

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