[英]changing background color of a table column javascript
我想為每個數字設置3和2的倍數的背景色,我該怎么做? 我不太擅長使用JavaScript
HTML:
<div id="mainDiv">
<input type="text" id="myNo" />
<input type="button" id="gridSize" value="Show It" />
</div>
使用Javascript:
var button = document.getElementById('gridSize');
button.onclick = function(e){
result = document.getElementById('result');
num = parseInt(document.getElementById('myNo').value);
alert(num);
if ( isNaN(num) ){
alert("No Numeric Value!");
}
else{
result.innerHTML = num;
}
var str = "<table border='2'>";
for (row = 0; row < num; row++){
str += "<tr>";
for (col = 0; col < num; col++){
str += "<td>";
var randNum = Math.floor(Math.random() * 100) + 1;
if (randNum % 2){
console.log(randNum + "Red");
}
str += randNum;
str += "</td>";
}
str += "</tr>";
}
str = str + "</table>";
result.innerHTML = str;
}
這是您檢查的方式(如果可以將其除以2和3):
if(randNum %2===0 && randNum %3===0){
// do some
}
如果將td創建的內容放入if else語句中,則可以像下面這樣簡單地進行操作:
HTML
<div id="mainDiv">
<input type="text" id="myNo" />
<input type="button" id="gridSize" value="Show It" />
</div>
<div id="result"></div>
CSS
.two {
background: red;
}
.three {
background: blue;
}
JS
var button = document.getElementById('gridSize');
button.onclick = function(e) {
result = document.getElementById('result');
num = parseInt(document.getElementById('myNo').value);
alert(num);
if (isNaN(num)) {
alert("No Numeric Value!");
} else {
result.innerHTML = num;
}
var str = "<table border='2'>";
for (row = 0; row < num; row++) {
str += "<tr>";
for (col = 0; col < num; col++) {
var randNum = Math.floor(Math.random() * 100) + 1;
if (randNum % 2 === 0) {
str += '<td class="two">';
} else if (randNum % 3 === 0) {
str += '<td class="three">';
} else {
str += "<td>";
}
str += randNum + "</td>";
}
str += "</tr>";
}
str = str + "</table>";
result.innerHTML = str;
}
jsfiddle 在這里
這是您可以執行此操作的方法(類似於您的代碼)
var resultTable = document.createElement('table');
var tr = resultTable.insertRow();
tbl.style.border = '1px solid black';
for (row = 0; row < num; row++){
var tr = resultTable.insertRow();
for (col = 0; col < num; col++){
var td = tr.insertCell();
var randNum = Math.floor(Math.random() * 100) + 1;
//for example if you want numbers countable with 2 to be red
if ((randNum % 2) === 0){
td.style.backgroundColor = "red";
}
td.appendChild(document.createTextNode(randNum.toString()));
}
}
result.appendChild(resultTable);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.