【发布时间】:2017-04-04 15:05:24
【问题描述】:
这里我有一个文本框,它接受一个数字,然后在单击按钮后根据该数字显示一个带有随机数字的表格。完成后,现在我想要实现的基本上是添加蓝色或红色,如果单元格内的随机数是 (num % 3 == 0) 或 (num % 2 == 0)。然后稍后显示表格下方所有数字的平均值。我已经坚持了一段时间了,所以我想我寻求帮助。关于如何解决这个问题的任何提示?
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 很抱歉,我没有注意到我没有包括右花括号。谢谢
标签: javascript