gpt4 book ai didi

javascript - 更改表格列javascript的背景颜色

转载 作者:行者123 更新时间:2023-11-30 16:10:12 25 4
gpt4 key购买 nike

我想为每个 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;
}

最佳答案

如果你将你的 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 here

关于javascript - 更改表格列javascript的背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36378510/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com