// This code segment is displayed in IE9, Firefox, Chorme, and safair tests. Some simple styles are added to the table, and basic functions can be implemented. There are still a few issues to be improved!
As follows:
The following code is used:
Copy codeThe Code 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 a json array to a table </title>
<Meta http-equiv = "content-type" content = "text/html; charset = gb2312">
<Style type = "text/css">
Caption {
Padding: 0 0 5px 0;
Width: pixel PX;
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: 'run', age: 20, gender: 'female'}];
// Execute the onload event after the webpage is loaded
Onload = function (){
Var body = document. getElementsByTagName ('body') [0];
Body. appendChild (createTable (data ));
};
// Create a table based on the input json Array
Var createTable = function (data ){
// Define a table
Var table = document. createElement ('table ');
Table. setAttribute ('style', 'width: pixel ;');
// Define the table title
Var caption = document. createElement ('caption ');
Caption. innerHTML = 'student info table ';
// Add the title to the table
Table. appendChild (caption );
// Call the createTr () method to generate the title row and add it to the table.
Table. appendChild (createTr ('name', 'age', 'Gender '));
Table. childNodes [1]. setAttribute ('style', 'background: # cae8ea ;');
// Alert (table. firstChild );
// For Loop the json object, and then generate the row of the object to be recycled through the createTr () method, and add the row 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;
};
// Generate a table row based on the variable passed by the user
Var createTr = function (name, age, gender ){
// Define the 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 the column value to the Row Element Node
Tr. appendChild (tdName );
Tr. appendChild (tdAge );
Tr. appendChild (tdGender );
// Return the generated row label
Return tr;
};
</Script>
</Head>
<Body>
</Body>
</Html>