This code in IE9, Firefox, Chorme, Safair test shows no problem, to the table to add some simple style, basic functions can be achieved, there are a few problems to be improved!
The effect chart is as follows:
Here's the code:
Copy Code code as follows:
<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">
<title>json Arrays into tables </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 Web page has finished loading
onload = function () {
var body=document.getelementsbytagname (' body ') [0];
Body.appendchild (createtable (data));
};
Create a table from an incoming JSON array
var createtable = function (data) {
Definition table
var table=document.createelement (' table ');
Table.setattribute (' style ', ' width:450px; ');
Define table Headers
var caption=document.createelement (' caption ');
caption.innerhtml = ' Student Information table ';
Add a caption to a table
Table.appendchild (caption);
Call the Createtr () method to generate the header row and add it to the table.
Table.appendchild (Createtr (' name ', ' age ', ' sex '));
Table.childnodes[1].setattribute (' style ', ' background: #cae8ea; ');
alert (table.firstchild);
For loop JSON object, and then the loop to object is born through the Createtr () method and added to the table
for (Var i=0;i<data.length;i++) {
Table.appendchild (CREATETR (Data[i].name,data[i].age,data[i].gender));
}
return table;
};
Method of generating a table row based on a variable passed by a user
var createtr = function (Name,age,gender) {
Define row element Labels
var tr=document.createelement (' tr ');
Define Column element labels
var tdname=document.createelement (' TD ');
Sets the value of the text node for this column node
tdname.innerhtml = name;
var tdage = document.createelement (' TD ');
Tdage.innerhtml = age;
var tdgender = document.createelement (' TD ');
Tdgender.appendchild (document.createTextNode (gender));//equivalence and tdgender.innerhtml = gender;
To add a column value to a row element node
Tr.appendchild (Tdname);
Tr.appendchild (Tdage);
Tr.appendchild (Tdgender);
Returns the generated row label
return TR;
};
</script>
<body>
</body>