关于如何在javascript中组合这两个函数的提示?



我为odin项目制作了一个蚀刻草图,但我被告知我可以使用参数组合我的createGrid()和updateGrid()函数。我该怎么做呢?更新网格功能是允许用户输入任意数字并更改网格大小。

const grid = document.querySelector(".gridContainer");
const userInput = document.getElementById("quantity");
const clear = document.querySelector(".clear");

const createGrid = () => {
for(let i = 0; i < 256; i++) {
const div = document.createElement("div");
div.classList.add("square");
grid.appendChild(div);

div.addEventListener("mouseenter", function () {
div.style.backgroundColor = randomColor();
});
}
};
const updateGrid = () => {
grid.innerHTML="";
grid.style.setProperty(
"grid-template-columns",
`repeat(${userInput.value}, 1fr)`
);
grid.style.setProperty(
"grid-template-rows",
`repeat(${userInput.value}, 1fr)`
);
for (let i = 0; i< userInput.value * userInput.value; i++){
const div=document.createElement("div");
div.classList.add("square");
grid.appendChild(div);
div.addEventListener("mouseenter", function () {
div.style.backgroundColor = randomColor();
});
}
};
userInput.addEventListener("change", updateGrid);
function randomColor() {
const randomRed = Math.floor(Math.random() * 256);
const randomGreen = Math.floor(Math.random() * 256);
const randomBlue = Math.floor(Math.random() * 256);
return `rgb(${randomRed}, ${randomGreen},${randomBlue})`;
}

clear.addEventListener("click", function() {
grid.innerHTML = "";
userInput.value = "";
grid.style.setProperty("grid-template-columns", `repeat(16, 1fr)`);
grid.style.setProperty("grid-template-rows", `repeat(16, 1fr)`);
createGrid();
});
createGrid();


createGrid取一个参数,即要制作的正方形数:

const createGrid = (limit = 256) => {
for (let i = 0; i < limit; i++) {
const div = document.createElement("div");
div.classList.add("square");
grid.appendChild(div);
div.addEventListener("mouseenter", function () {
div.style.backgroundColor = randomColor();
});
}
};
const updateGrid = () => {
grid.innerHTML = "";
grid.style.setProperty(
"grid-template-columns",
`repeat(${userInput.value}, 1fr)`
);
grid.style.setProperty(
"grid-template-rows",
`repeat(${userInput.value}, 1fr)`
);
createGrid(Number(userInput.value));
};

最新更新