DIV CSS 佈局教程網

JavaScript動態創建表格及添加數據實例詳解
編輯:JavaScript綜合知識     

本文分享JavaScript動態創建表格及添加數據的方法,供有需要的朋友參考。具體分析如下:

1. 動態創建表格(代碼不兼容IE6)

<html xmlns="https://www.w3.org/1999/xhtml">
<head>
  <title>動態創建表格</title>
  <script type="text/javascript">
  function AppendTableData() {
    var table = document.getElementById("tblMain");
    var data = { "百度": "https://www.baidu.com", "三聯": "https://www.3lian.net", "搜狐": "https://www.sohu.com" };
    for (var key in data) {
      var tr = document.createElement("tr");
      var td1 = document.createElement("td");
      td1.innerText = key;
      tr.appendChild(td1);
      var td2 = document.createElement("td");
      td2.innerHTML = "<a href='" + data[key] + "'>" + data[key] + "</a>";
      tr.appendChild(td2);
      table.appendChild(tr);
    }
  }
  </script>
</head>
<body>
  <table id="tblMain"></table>
  <input type="button" value="動態添加網格數據" onclick="AppendTableData()" />
</body>
</html>

2. 動態創建表格(兼容IE6、IE7)

<html xmlns="https://www.w3.org/1999/xhtml">
<head>
  <title>添加網格數據(處理了IE兼容問題)</title>
  <script type="text/javascript">
  function AppendData() {
    var data = {"三聯":"https://www.3lian.net", "百度":"https://www.baidu.com", "搜狐": "https://www.sohu.com"};
    var table = document.getElementById("tblMain");
    for (var key in data) {
      var value = data[key];
      var tr = table.insertRow(-1); // FireFox必須使用-1這個參數
      var td1 = tr.insertCell(-1);
      td1.innerText = key;
      var td2 = tr.insertCell(-1);
      td2.innerHTML = "<a href='" + value + "'>" + value + "</a>";
    }
  }
  </script>
</head>
<body>
  <table border="1" id="tblMain"></table>
  <input type="button" value="添加網格數據(處理了IE兼容問題)" onclick="AppendData()" />
</body>
</html>

3. 動態創建表格(處理IE6的tbody問題)

<html xmlns="https://www.w3.org/1999/xhtml">
<head>
  <title>動態創建表格(處理IE6兼容問題)</title>
  <script type="text/javascript">
  function AppendTableData() {\br />    var table = document.getElementById("tblMain");
    var data = { "百度": "https://www.baidu.com", "三聯": "https://www.3lian.net", "搜狐": "https://www.sohu.com" };
    for (var key in data) {\br />      var tr = document.createElement("tr");
      var td1 = document.createElement("td");
      td1.innerText = key;
      tr.appendChild(td1);
      var td2 = document.createElement("td");
      td2.innerHTML = "<a href='" + data[key] + "'>" + data[key] + "</a>";
      tr.appendChild(td2);
      // 把 table.appendChild(tr) 替換為下面這句
      table.tBodies[0].appendChild(tr);
    }
  }
  </script>
</head>
<body>
  <!-- 由於動態添加的數據會自動生成一個空的tbody,把我們生成的數據沖掉,所以手工添加一個tbody,tr添加到這個tbody下面 -->
  <table id="tblMain"><tbody></tbody></table>
  <input type="button" value="動態添加網格數據" onclick="AppendTableData()" />
</body>
</html>

希望本文所述對大家的JavaScript程序設計有所幫助。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved