HTML DOM TableRow insertCell() 方法

HTML DOM TableRow insertCell() 方法

HTML DOM TableRow.insertCell() 方法用于在表格行 () 中插入一个或多个新单元格 (),并返回对该单元格的引用。

该方法接受一个参数”index”,表示新单元格的位置;如果提供的值为-1或等于单元格的数量,新单元格将被插入为行中的最后一个单元格。如果提供的位置值为0,新单元格将被插入为第一个单元格。如果不提供位置参数,默认值为-1。

语法

以下是HTML DOM TableRow.insertCell() 方法的语法−

Tablerowobject.insertCell(index);

其中,index是一个可选参数,表示新单元格的单元格索引。

注意 - 在像Firefox和Opera这样的浏览器中,此参数是必需的,但在Internet Explorer、Chrome和Safari中是可选的。

示例

在以下示例中,我们使用DOM TableRow.insertcell()方法从索引位置”1″插入新的单元格。

<!DOCTYPE html>
<html>
<head>
   <style>
      table {
         border-collapse: collapse;
         width: 50%;
      }
      table td {
         border: 1px solid black;
         padding: 8px;
         text-align: center;
      }
      table th {
         border: 1px solid black;
         padding: 8px;
         text-align: center;
         background-color: #f2f2f2;
      }
   </style>
</head>
<body>
   <p>Click the button to insert new cell(s) from index "1".</p>
   <table>
      <tr id="myRow">
         <th>Cell 1</th>
         <th>Cell 2</th>
         <th>Cell 3</th>
      </tr>
   </table><br>
   <button onclick="insertNewCell()">Click to ADD</button>
   <script>
      function insertNewCell() {
         var rowElement = document.getElementById("myRow");
         var cellElement = rowElement.insertCell(1);
         cellElement.innerHTML = "New cell";
      }
   </script>
</body>
</html>

执行上述程序后,每当点击按钮时,它将从索引位置”1″添加新的单元格。

示例

在下面的示例中,我们从表行的最后位置插入新的单元格-

<!DOCTYPE html>
<html>
<head>
   <style>
      table {
         border-collapse: collapse;
         width: 50%;
      }

      table td {
         border: 1px solid black;
         padding: 8px;
         text-align: center;
      }

      table th {
         border: 1px solid black;
         padding: 8px;
         text-align: center;
         background-color: #f2f2f2;
      }
   </style>
</head>
<body>
   <p>Click the button to insert new cell(s) from from last position</p>
   <table>
      <tr id="myRow">
         <th>Cell 1</th>
         <th>Cell 2</th>
         <th>Cell 3</th>
      </tr>
   </table><br>
   <button onclick="insertNewCell()">Click to ADD</button>
   <script>
      function insertNewCell() {
         var rowElement = document.getElementById("myRow");
         var cellElement = rowElement.insertCell(-1);
         cellElement.innerHTML = "New cell";
      }
   </script>
</body>
</html>

每当我们点击按钮时,tablerow.insertcell()方法将从表格行的最后位置插入行。

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程

HTML 精选笔记