ここでは、ボタンをクリックした後に乱数を持つテーブルを表示する数値をとるテキストボックスがあります。それで、今私が達成しようとしているのは、セル内の乱数が(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