Js generates dynamic tables and adds methods for click events for each cell

  • 2020-03-30 02:38:51
  • OfStack

HTML:
 
<html> 
<head> 
<title>Demo</title> 
</head> 
<body> 
<label style="font-size:20px;width:600px;" > Dynamic table: </label><br/> 
<table border="1"> 
<tbody id="table"> 
</table> 
</body> 
</html> 

Script:
 
<script> 
function getColumnDetail(column){ 
column.style.color = "blue"; //Sets the cell being clicked to blue
alert(column.innerHTML); //Pops up the contents of the clicked cell
} 
<!--trLineNumber Is the number of dynamic table rows, tdData Is the data of each row cell in the dynamic table, and the data type is an array --> 
function setTable(trLineNumber,tdData){ 
var _table = document.getElementById("table"); 
var _row; 
var _cell; 
for (var i = 0; i < trLineNumber; i++) { 
_row = document.createElement("tr"); 
document.getElementById("table").appendChild(_row); 
for(var j = 0; j < tdData.length; j++) { 
_cell = document.createElement("td"); 
_cell.onclick= function(){getColumnDetail(this)}; //Adds a click event for each cell
_cell.innerText = tdData[j]; 
_row.appendChild(_cell); 
} 

} 
} 
</script> 

The function setTable(trLineNumber,tdData) is called to dynamically generate a table, and a click event is set for each cell. When triggered, the contents of the clicked cell pop up and the data turns blue

Related articles: