Javascript dynamically adds table implementation code to a web page


// 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:   Here’s the code:


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<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;
width:150px;
}
</style>
<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];
body.appendChild(createTable(data));
};

//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
table.appendChild(caption);
//Call the createTr() method to generate the header line and add it to the table.
table.appendChild(createTr(' The name ',' age ',' gender '));
table.childNodes[1].setAttribute('style','background:#cae8ea;');
//alert(table.firstChild);
//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++){
table.appendChild(createTr(data[i].name,data[i].age,data[i].gender));
}
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
tr.appendChild(tdName);
tr.appendChild(tdAge);
tr.appendChild(tdGender);

//Returns the generated row label
return tr;
};
</script>
</head>
<body>
</body>
</html>