當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


HTML DOM Table用法及代碼示例


Table對象用於表示HTML <table>元素。它可用於創建和訪問表。

用法:

  • 要訪問表元素:
    document.getElementById("id");
  • 要創建表對象:
    document.createElement("TABLE");

以下示例程序旨在說明Table對象:

示例1:通過使用getElementById()方法訪問<table>元素。

<!DOCTYPE html> 
<html> 
  
<head> 
    <title>Table Object in HTML</title> 
    <style> 
        table, 
        td { 
            border:1px solid green; 
        } 
          
        h1 { 
            color:green; 
        } 
          
        h2 { 
            font-family:Impact; 
        } 
          
        body { 
            text-align:center; 
        } 
    </style> 
</head> 
  
<body> 
  
    <h1>GeeksforGeeks</h1> 
    <h2>Table Object</h2> 
    <br> 
  
    <table id="table" align="center"> 
        <tr> 
            <td>Fork Python</td> 
            <td>Fork Java</td> 
        </tr> 
        <tr> 
            <td>Sudo Placement</td> 
            <td>Fork CPP</td> 
        </tr> 
    </table> 
  
    <p>Double click the "Delete Row"  
      button to remove the second row from the table.</p> 
  
    <button onclick="delete()">Delete Row</button> 
  
    <script> 
        function delete() { 
            
            // Accessing table object. 
            var x = document.getElementById("table"); 
            x.deleteRow(0); 
        } 
    </script> 
  
</body> 
  
</html>

輸出:
單擊按鈕之前:



單擊按鈕後:

示例-2:使用document.createElement()方法創建<table>元素。

<!DOCTYPE html> 
<html> 
  
<head> 
    <title>Table Object in HTML</title> 
    <style> 
        table { 
            border:1px solid green; 
        } 
          
        h1 { 
            color:green; 
        } 
          
        h2 { 
            font-family:Impact; 
        } 
          
        body { 
            text-align:center; 
        } 
    </style> 
</head> 
  
<body> 
  
    <h1>GeeksforGeeks</h1> 
    <h2>Table Object</h2> 
    <br> 
  
    <p>Double click the "Create" button to create a  
      TABLE, a Table row and a Table cell element.</p> 
  
    <button ondblclick="create()">Create</button> 
  
    <script> 
        function create() { 
            
            // Create table object. 
            var a = document.createElement("TABLE"); 
            a.setAttribute("id", "MyTable"); 
            document.body.appendChild(a); 
  
            var b = document.createElement("TR"); 
            b.setAttribute("id", "MyTr"); 
            document.getElementById("MyTable").appendChild(b); 
  
            var c = document.createElement("TD"); 
            var d = document.createTextNode("Table cell"); 
            c.appendChild(d); 
            document.getElementById("MyTr").appendChild(c); 
        } 
    </script> 
  
</body> 
  
</html>

輸出:
單擊按鈕之前:

單擊按鈕後:

支持的瀏覽器:

  • Opera
  • IE瀏覽器
  • 穀歌瀏覽器
  • Firefox
  • 蘋果Safari

相關用法


注:本文由純淨天空篩選整理自Shubrodeep Banerjee大神的英文原創作品 HTML | DOM Table Object。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。