Home > Web Front-end > JS Tutorial > body text

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

WBOY
Release: 2016-05-16 15:24:32
Original
1525 people have browsed it

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>
Copy after login

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.

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!