更改表列javascript的背景颜色

时间:2016-04-02 20:44:25

标签: 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;
}

3 个答案:

答案 0 :(得分:1)

这是你检查的方式,如果是的话 可分为2和3:

INSERT INTO word_relations(word1_id, word2_id, score) VALUES($1, $2, $3)
ON CONFLICT (word1_id, word2_id) DO UPDATE SET score = score + $3`)

答案 1 :(得分:1)

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

答案 2 :(得分:0)

这是你可以做到的方式(类似于你的代码)

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);