這裏我有一個文本框,它需要一個數字,然後根據點擊按鈕後顯示隨機數字的表格。這樣做,現在我想要實現的基本上是添加藍色或紅色,如果單元格內的隨機數是(num%3 == 0)或(num%2 == 0)。然後再顯示錶格下方所有數字的平均值。我一直堅持這一段時間,所以我想我尋求幫助。關於如何處理這個問題的任何提示?根據條件指定表格單元格的顏色 - JavaScript
var min = 1;
var max = 100;
function drawTable() {
//Get the div reference for the body
var div1 = document.getElementById('tableDiv');
//Creates a table element
var tbl = document.createElement("table");
var totalRows = parseInt(document.getElementById("inputBox").value);
var cellsInRow = parseInt(document.getElementById("inputBox").value);
//Creating rows
for (var rows = 0; rows < totalRows; rows++) {
var row = document.createElement("tr");
/*if (rows % 3 == 0)
{
//background
bg = "class='red'";
}
else {
bg = "class='blue'";
}*/
//Create cells in row
for (var cells = 0; cells < cellsInRow; cells++) {
var cell = document.createElement("td");
getRandom = Math.floor(Math.random() * (max - min + 1)) + min;
var cellText = document.createTextNode(Math.floor(Math.random() * (max - min + 1)) + min);
cell.appendChild(cellText);
row.appendChild(cell);
}
//Add the row to the end of the table body
tbl.appendChild(row);
}
//Appends <table> into the <div>
div1.appendChild(tbl);
}
<input type="text" value="" id="inputBox">
<input type="button" value="Generate Grid" id="generateBtn" onclick="drawTable()">
<div id="tableDiv">
</div>
我剛剛更新你的問題包括MCVE。在提出問題之前,請記得檢查您的代碼是否真正運行 - 我必須在代碼末尾添加缺少的結束括號。 – Terry
@Terry對不起,我沒有注意到我沒有包括大括號。謝謝 – Maxlong007