1. 交互性。在和用户的交互中收集数据来生成表格,这个是传统方式所不能完成的。
2. 灵活性。通过JavaScript生成的表格是面向对象的,可以非常容易的实现表格属性的修改。比如把特定的某些行或者列的背景变色,只需通过其对象调用改变即可,下面的例子会有体现。如果通过传统的方式的话,就需要进行令人头大的字符串拼接了。
下面的例子实现对一个规则的哈希结构进行动态的表格转化。
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head>
- <title>Summary</title>
- <script type="text/javascript">
- function create_table() {
- var summary = [
- {
- "name":"zhang san",
- "age":24
- },
- {
- "name":"li si",
- "age":42
- },
- {
- "name":"wang wu",
- "age":34
- }
- ];
- var mytable = document.createElement("table");
- var mytablebody = document.createElement("tbody");
- var mycurrent_row,key;
- //create the table header
- var item = summary[0];
- mycurrent_row = document.createElement("tr");
- for (key in item) {
- mycurrent_cell = document.createElement("td");
- currenttext = document.createTextNode(key);
- mycurrent_cell.appendChild(currenttext);
- mycurrent_row.appendChild(mycurrent_cell);
- }
- mytablebody.appendChild(mycurrent_row);
-
- for(var x=0;x<summary.length;x++){
- item = summary[x];
- mycurrent_row = document.createElement("tr");
- for (key in item) {
- mycurrent_cell = document.createElement("td");
- currenttext = document.createTextNode(item[key]);;
- mycurrent_cell.appendChild(currenttext);
- mycurrent_row.appendChild(mycurrent_cell);
- }
- if(x % 2 == 0) mycurrent_row.style.backgroundColor = "yellow";
- mytablebody.appendChild(mycurrent_row);
- }
-
-
- mytable.appendChild(mytablebody);
- mytable.setAttribute("border", "2");
- return mytable;
- }
- window.onload = function(){
- var table=create_table();
- document.body.appendChild(table);
- }
- </script>
- </head>
- <body>
- </body>
- </html>