DOM TableRow insertCell() 方法

htmlweb developmentfront end technology更新于 2024/11/16 11:24:17

HTML DOM TableRow.insertCell() 方法用于将新单元格 (<td>) 插入表格行 (<tr>),并返回该单元格的引用。

此方法接受一个参数"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() 方法就会从表格行的最后一个位置插入行。


相关文章


有用资源