//This code was tested in IE9, Firefox, Chorme, and safair and showed no problems. I added some simple styles to the table. The basic functions can be implemented, and there are still a few problems that need to be improved!
The renderings are as follows:
Here is the code:
The code copy is as follows:
<!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>Convert json array into 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'}];
//The onload event is executed after the web page is loaded.
onload = function(){
var body=document.getElementsByTagName('body')[0];
body.appendChild(createTable(data));
};
//Create a table based on the passed json array
var createTable = function(data){
//Define the table
var table=document.createElement('table');
table.setAttribute('style','width: 450px;');
//Define the table title
var caption=document.createElement('caption');
caption.innerHTML = 'Student Information Table';
//Add the title into the table
table.appendChild(caption);
//Call createTr() method to generate the title line and add it to the table.
table.appendChild(createTr('name','age','gender'));
table.childNodes[1].setAttribute('style','background:#cae8ea;');
//alert(table.firstChild);
//For loop json object, then the looped object is generated by creatingTr() 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;
};
//How to generate rows in a table based on the variables sent by the user
var createTr = function(name,age,gender){
//Define row element label
var tr=document.createElement('tr');
//Define the column element label
var tdName=document.createElement('td');
//Set 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));//Equivalent to tdGender.innerHTML = gender;
//Add column value to row element node
tr.appendChild(tdName);
tr.appendChild(tdAge);
tr.appendChild(tdGender);
//Return the generated row label
return tr;
};
</script>
</head>
<body>
</body>
</html>