Javascript dynamically adds table implementation code to a web page

  • 2020-03-30 01:47:04
  • OfStack

// this code in IE9, Firefox, Chorme, safair tests show no problems, to the table to add some simple style, basic functions can be achieved, there are a few problems to be improved!

The effect drawing is as follows:
< img SRC = "border = 0 / / 2014119152751 ">  
Here's the code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" ""> 
<html xmlns=""> 
<title>json Array into a table </title> 
<meta http-equiv="content-type" content="text/html;charset=gb2312"> 
<style type="text/css"> 
caption { 
padding: 0 0 5px 0; 
width: 450px; 
font: italic 11px "Trebuchet MS", Verdana, Arial, Helvetica, sans-serif; 
text-align: right; 
td { 
border:1px solid #c1dad7; 

padding: 6px 6px 6px 12px; 
color: #4f6b72; 
text-align: center; 
<script type="text/javascript"> 
var data=[{name:'xiaoxiao',age:12,gender:'male'},{name:'xiao',age:22,gender:'male'},{name:'hh',age:12,gender:'female'},{name:'ran',age:20,gender:'female'}]; 

//Execute the onload event after the page is loaded
onload = function(){ 
var body=document.getElementsByTagName('body')[0]; 

//Create the table from the json array passed in
var createTable = function(data){ 

//Define the form
var table=document.createElement('table'); 
table.setAttribute('style','width: 450px;'); 

//Define table titles
var caption=document.createElement('caption'); 
caption.innerHTML =' Student information sheet '; 

//Adds the title to the table
//Call the createTr() method to generate the header line and add it to the table.
table.appendChild(createTr(' The name ',' age ',' gender ')); 
//For loops the json object, and then adds the loop object to the table by generating rows through the createTr() method
for(var i=0;i<data.length;i++){ 
return table; 

//A method to generate rows in a table based on the variables passed by the user
var createTr = function(name,age,gender){ 
//Defines the row element label
var tr=document.createElement('tr'); 
//Define the column element tag
var tdName=document.createElement('td'); 
//Sets the value of the text node of the column node
tdName.innerHTML = name; 
var tdAge = document.createElement('td'); 

tdAge.innerHTML = age; 
var tdGender = document.createElement('td'); 

tdGender.appendChild(document.createTextNode(gender));//Tdgene.innerhtml = gender;
//Adds the column value to the row element node

//Returns the generated row label
return tr; 

Related articles: