js实现表格添加,删除选中数据并带样式设置
时间: 2024-03-01 21:53:30 浏览: 19
实现表格添加、删除选中数据并带样式设置的示例代码如下:
HTML:
```html
<table id="myTable">
<thead>
<tr>
<th>Name</th>
<th>Age</th>
<th>Gender</th>
</tr>
</thead>
<tbody>
<tr>
<td>John Smith</td>
<td>32</td>
<td>Male</td>
</tr>
<tr>
<td>Jane Doe</td>
<td>28</td>
<td>Female</td>
</tr>
<tr>
<td>Bob Johnson</td>
<td>45</td>
<td>Male</td>
</tr>
</tbody>
</table>
<form id="myForm">
<input type="text" name="name" placeholder="Name">
<input type="text" name="age" placeholder="Age">
<select name="gender">
<option value="male">Male</option>
<option value="female">Female</option>
</select>
<button type="submit" onclick="addRow()">Add</button>
<button type="button" onclick="deleteSelectedRows()">Delete Selected</button>
</form>
```
JavaScript:
```javascript
// 添加行
function addRow() {
// 获取表单数据
const form = document.getElementById("myForm");
const name = form.elements["name"].value;
const age = form.elements["age"].value;
const gender = form.elements["gender"].value;
// 创建新行
const table = document.getElementById("myTable");
const row = table.insertRow(-1);
const cell1 = row.insertCell(0);
const cell2 = row.insertCell(1);
const cell3 = row.insertCell(2);
cell1.innerHTML = name;
cell2.innerHTML = age;
cell3.innerHTML = gender;
// 设置样式
row.style.backgroundColor = "#f2f2f2";
}
// 删除选中行
function deleteSelectedRows() {
const table = document.getElementById("myTable");
const rows = table.getElementsByTagName("tr");
for (let i = 0; i < rows.length; i++) {
const row = rows[i];
const checkbox = row.getElementsByTagName("input")[0];
if (checkbox && checkbox.checked) {
table.deleteRow(i);
i--;
}
else {
row.style.backgroundColor = "white";
}
}
}
// 初始化表格
const table = document.getElementById("myTable");
const rows = table.getElementsByTagName("tr");
for (let i = 0; i < rows.length; i++) {
const row = rows[i];
row.onclick = function() {
const checkbox = this.getElementsByTagName("input")[0];
if (checkbox) {
checkbox.checked = !checkbox.checked;
this.style.backgroundColor = checkbox.checked ? "#f2f2f2" : "white";
}
}
}
```
以上代码实现了一个简单的表格添加、删除选中数据并带样式设置的功能。其中 `addRow()` 函数用于添加新行,`deleteSelectedRows()` 函数用于删除选中行。在添加新行时,我们获取表单数据,创建新行并插入到表格中,最后设置新行的样式。在删除选中行时,我们遍历表格中的行,获取复选框元素,如果该行的复选框被选中,则删除该行,否则恢复该行的样式。在初始化表格时,我们为每一行添加点击事件,获取对应的复选框元素,如果复选框被选中,则设置该行的样式为选中状态,否则恢复该行的样式。