用js写一个table的插件,可以自由删除列和行,表格内容可编辑的
时间: 2024-03-12 13:43:48 浏览: 53
好的,以下是一个简单的JS实现的表格插件,可以自由删除列和行,表格内容可编辑:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Table Plugin</title>
<style>
table {
border-collapse: collapse;
width: 100%;
text-align: center;
}
td, th {
border: 1px solid black;
padding: 5px;
}
.delete {
color: red;
cursor: pointer;
}
</style>
</head>
<body>
<table id="my-table">
<thead>
<tr>
<th>Header 1</th>
<th>Header 2</th>
<th>Header 3</th>
</tr>
</thead>
<tbody>
<tr>
<td contenteditable="true">Cell 1</td>
<td contenteditable="true">Cell 2</td>
<td contenteditable="true">Cell 3</td>
</tr>
<tr>
<td contenteditable="true">Cell 4</td>
<td contenteditable="true">Cell 5</td>
<td contenteditable="true">Cell 6</td>
</tr>
</tbody>
</table>
<br>
<button onclick="addRow()">Add Row</button>
<button onclick="addColumn()">Add Column</button>
</body>
<script>
// 删除列
function deleteColumn() {
var table = document.getElementById("my-table");
var column = prompt("Please enter the column number you want to delete:", "");
if (column != null && column != "") {
var columnIndex = parseInt(column, 10);
if (columnIndex < table.rows[0].cells.length) {
for (var i = 0; i < table.rows.length; i++) {
table.rows[i].deleteCell(columnIndex);
}
} else {
alert("Invalid column number!");
}
}
}
// 删除行
function deleteRow() {
var table = document.getElementById("my-table");
var row = prompt("Please enter the row number you want to delete:", "");
if (row != null && row != "") {
var rowIndex = parseInt(row, 10);
if (rowIndex < table.rows.length) {
table.deleteRow(rowIndex);
} else {
alert("Invalid row number!");
}
}
}
// 添加列
function addColumn() {
var table = document.getElementById("my-table");
var headerRow = table.rows[0];
var newColumn = prompt("Please enter the header text for the new column:", "");
if (newColumn != null && newColumn != "") {
var newCell = headerRow.insertCell(-1);
newCell.innerHTML = newColumn + "<span class='delete' onclick='deleteColumn()'>X</span>";
for (var i = 1; i < table.rows.length; i++) {
var row = table.rows[i];
var newCell = row.insertCell(-1);
newCell.contentEditable = "true";
}
}
}
// 添加行
function addRow() {
var table = document.getElementById("my-table");
var newRow = table.insertRow(-1);
for (var i = 0; i < table.rows[0].cells.length; i++) {
var newCell = newRow.insertCell(-1);
newCell.contentEditable = "true";
}
}
</script>
</html>
```
在这个插件中,我们使用了`contenteditable`属性使表格内容可编辑。我们还使用了`prompt`函数来获取用户输入的行和列的索引,并使用`insertRow`、`insertCell`、`deleteRow`和`deleteCell`函数来操作表格。我们还添加了一个`span`元素,在添加列时将其添加到表头单元格中,在单元格的文本后面显示一个`X`,以便用户点击删除列。
阅读全文