[英]How can i make the clear button work properly on this code?
我正在嘗試做一個簡單的程序來填充一些 div,我需要一個重置按鈕才能清除所有充滿內容的 div,這樣用戶就可以再次在 div 上輸入。 這是我的代碼:
// **reset function**:
const clearAll = document.getElementsByClassName("clear");
clearAll.addEventListener('click', clearCells);
function clearCells(){
for (let i = 0; i < cells.length; i++){
cells[1] = "green";
}
}
很抱歉這個菜鳥問題,仍在嘗試解決一些問題。
//default color let fillColor = "red"; //select all colors const colorDivs = document.querySelectorAll(".colors"); //listen to all colors if one of them clicked colorDivs.forEach(function (color) { color.addEventListener("click", pickColor); }) //take the color of it and put it in fillColor function pickColor(event) { fillColor = event.target.style.backgroundColor; } //select all colors const cells = document.querySelectorAll(".cell"); //listen to all cells if one of them clicked cells.forEach(function (cell) { cell.addEventListener("click", paintCell); }) //color it with the fillColor picked function paintCell(event) { event.target.style.backgroundColor=fillColor; } //get the button clear All const clearAll = document.getElementsByClassName("clear")[0]; //if clicked clearAll.addEventListener('click', clearCells); //set all cells to white color function clearCells(){ for (let i = 0; i < cells.length; i++){ cells[i].style.backgroundColor = "white"; } }
table, tr, td { font-size: 24px; border: 1px solid black; border-collapse: collapse; } td { height: 70px; width: 80px; text-align: center; cursor: pointer; }.colors{ width: 50px; height: 50px; display: inline-block; cursor: pointer; } button{ background-color: #4CAF50; /* Green */ border: none; color: white; padding: 15px 32px; text-align: center; text-decoration: none; display: inline-block; font-size: 16px; margin: 4px 2px; cursor: pointer; font-size: 24px; }
<div class="colors" style="background-color: red"></div> <div class="colors" style="background-color: green"></div> <div class="colors" style="background-color: blue"></div> <table> <tr> <td class='cell'>cell 1</td> <td class='cell'>cell 2</td> <td class='cell'>cell 3</td> </tr> <tr> <td class='cell'>cell 4</td> <td class='cell'>cell 5</td> <td class='cell'>cell 6</td> </tr> </table> <button class="clear">clear all</button>
編輯
getElementsByClassName 返回 class 明確的元素數組,因此您需要獲取第一個,否則您的 function 將永遠不會被調用
const clearAll = document.getElementsByClassName("clear")[0];
clearAll.addEventListener('click', clearCells);
第一次修復
cells[i].className = 'cell'
錯誤在最后一部分。
改變這個
// **reset function**:
const clearAll = document.getElementsByClassName("clear");
clearAll.addEventListener('click', clearCells);
function clearCells(){
for (let i = 0; i < cells.length; i++){
cells[1] = "white";
}
}
為了這:
// **reset function**:
document.getElementsByClassName("clear").forEach(function (cell) {
cell.addEventListener('click', clearCells);
});
function clearCells(){
cells.forEach(function (cell) {
cell.className = 'white';
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.