当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。