在单独的列中计算html表中一行的彩色单元格数量

时间:2019-01-22 12:49:01

标签: javascript html css

我有一个表,该表具有32列的列,起始31列的功能是我可以在单击任何单元格后填充颜色。请仅使用javascript。请参阅图片。

1 个答案:

答案 0 :(得分:0)

也许是这样的:

function set_random_color(){ /* for test only */
  var color_table = document.getElementById('color_table');
  var rnd_row_int = get_randon_cell_int();
  var rnd_color = '#'+(Math.random()*0xFFFFFF<<0).toString(16);
  color_table.rows[rnd_row_int].cells[0].setAttribute('bgcolor', rnd_color);
  get_count_white_cells();
}

function get_randon_cell_int(){
   var color_table = document.getElementById('color_table');
   var rnd_row_int = Math.floor(Math.random() * (color_table.rows.length-1));
   var cell_bgcolor = color_table.rows[rnd_row_int].cells[0].getAttribute('bgcolor'); 
   if(!cell_bgcolor){
      return rnd_row_int;  
   }else{
      return get_randon_cell_int();
   }
}

function get_count_white_cells(){
  var white_cell_counter = 0;
  var color_table = document.getElementById('color_table');
  for (var i = 0; i < color_table.rows.length-1; i++) {
     var cell_bgcolor = color_table.rows[i].cells[0].getAttribute('bgcolor');
     if (!cell_bgcolor){
        white_cell_counter++;
        
     }
  }
  color_table.rows[color_table.rows.length-1].cells[0].innerHTML = white_cell_counter;
  
  if(white_cell_counter == 0){
     alert('all cells colored!!!');
     document.getElementById('btn_set_color').setAttribute('onclick', 'alert(\'all cells colored!\')');
  }
}
table td {
    width: 20px;
    height: 20px;
}    
<input type="button" id="btn_set_color" value="set random cell color" onclick="set_random_color();">

<table border="1" id="color_table">
	<tr><td>&nbsp;</td></tr>
	<tr><td>&nbsp;</td></tr>
	<tr><td>&nbsp;</td></tr>
	<tr><td>&nbsp;</td></tr>
	<tr><td>&nbsp;</td></tr>
	<tr><td>&nbsp;</td></tr>
	<tr><td>&nbsp;</td></tr>
	<tr><td>&nbsp;</td></tr>
	<tr><td>&nbsp;</td></tr>
	<tr><td>&nbsp;</td></tr>
	<tr><td>&nbsp;</td></tr>
	<tr><td>&nbsp;</td></tr>
	<tr><td>&nbsp;</td></tr>
	<tr><td>&nbsp;</td></tr>
	<tr><td>&nbsp;</td></tr>
	<tr><td>&nbsp;</td></tr>
	<tr><td>&nbsp;</td></tr>
	<tr><td>&nbsp;</td></tr>
	<tr><td>&nbsp;</td></tr>
	<tr><td>&nbsp;</td></tr>
	<tr><td>&nbsp;</td></tr>
	<tr><td>&nbsp;</td></tr>
	<tr><td>&nbsp;</td></tr>
	<tr><td>&nbsp;</td></tr>
	<tr><td>&nbsp;</td></tr>
	<tr><td>&nbsp;</td></tr>
	<tr><td>&nbsp;</td></tr>
	<tr><td>&nbsp;</td></tr>
	<tr><td>&nbsp;</td></tr>
	<tr><td>&nbsp;</td></tr>
	<tr><td>&nbsp;</td></tr>
	<tr><td>&nbsp;</td></tr>   
</table>