Home  >  Article  >  Web Front-end  >  Dynamically create tables and increase the number of table rows based on JavaScript_javascript skills

Dynamically create tables and increase the number of table rows based on JavaScript_javascript skills

WBOY
WBOYOriginal
2016-05-16 15:24:321553browse

In work and project requirements, sometimes the number of rows in the table cannot meet our needs. At this time, we need to dynamically increase the number of rows in the table. The following editor will introduce to you through a code example how to create a table with js and add The number of rows in the table, and also implements the color changing function of alternate rows. Friends who are interested in this can refer to the code:

js code is as follows:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>动态操作表格</title>
</head>
<body>
<script type="text/javascript">
var n = 0;
function showTable(len) 
{
 wi('<table border="1" width="300" style="border-collapse:collapse"><tbody id="table">');
 for (i=0;i<len;i++) 
 {
 if (parseInt(i%2)==1) 
{
  bg = '#F4FAC7';
 } 
else 
{
  bg = 'white'; 
 }
 wi('<tr bgcolor='+bg+'><td>第'+(i+1)+'行</td></tr>'); 
 }
 wi('</tbody></table><br />');
 wi('<input type="button" value="Add" id="add" />'); 
}</P>
<P>function wi(str) 
{
 return document.write(str); 
}
showTable(10);
var add = document.getElementById("add");
 add.onclick = function() {
 n = n+1;
 if (n%2==0) 
 {
 bg = '#F4FAC7';
 } 
 else 
 {
 bg = 'white'; 
 }
 var table = document.getElementById("table");
 var tr = document.createElement("tr");
 tr.bgColor = bg;
 var td = document.createElement("td");
 td.innerHTML = '第'+(10+n)+'行';
 tr.appendChild(td);
 table.appendChild(tr);
}
</script>
</body>
</html>

The above content is related code to dynamically create tables and increase the number of table rows based on JavaScript. I hope you like it.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn