这里我有一个文本框,它需要一个数字,然后根据点击按钮后显示随机数字的表格。这样做,现在我想要实现的基本上是添加蓝色或红色,如果单元格内的随机数是(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