DOM 表格行 insertCell() 方法
HTML DOM TableRow.insertCell() 方法用于向表格行 (<tr>) 插入一个或多个新单元格 (<td>),并返回单元格的引用。
此方法接受一个参数“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() 方法都会从表格行的最后位置插入行。
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
安卓
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP