动态生成html表格 属性值为姓名邮箱电话实现添加删除
时间: 2024-03-09 14:48:03 浏览: 27
好的,我可以为您提供一种实现方式。您可以使用JavaScript动态生成HTML表格,并通过添加和删除按钮添加或删除表格行。以下是一个简单的实现示例:
HTML:
```html
<table id="contact-table">
<thead>
<tr>
<th>姓名</th>
<th>邮箱</th>
<th>电话</th>
<th>操作</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<button id="add-button">添加</button>
```
JavaScript:
```javascript
// 获取表格和添加按钮
const table = document.getElementById('contact-table');
const addButton = document.getElementById('add-button');
// 添加按钮点击事件
addButton.addEventListener('click', () => {
// 创建新行
const newRow = document.createElement('tr');
// 创建单元格
const nameCell = document.createElement('td');
const emailCell = document.createElement('td');
const phoneCell = document.createElement('td');
const deleteCell = document.createElement('td');
// 创建输入框和删除按钮
const nameInput = document.createElement('input');
const emailInput = document.createElement('input');
const phoneInput = document.createElement('input');
const deleteButton = document.createElement('button');
// 设置输入框和按钮属性
nameInput.setAttribute('type', 'text');
emailInput.setAttribute('type', 'email');
phoneInput.setAttribute('type', 'tel');
deleteButton.textContent = '删除';
// 将输入框和按钮添加到单元格中
nameCell.appendChild(nameInput);
emailCell.appendChild(emailInput);
phoneCell.appendChild(phoneInput);
deleteCell.appendChild(deleteButton);
// 将单元格添加到新行中
newRow.appendChild(nameCell);
newRow.appendChild(emailCell);
newRow.appendChild(phoneCell);
newRow.appendChild(deleteCell);
// 将新行添加到表格中
table.querySelector('tbody').appendChild(newRow);
// 添加删除按钮点击事件
deleteButton.addEventListener('click', () => {
newRow.remove();
});
});
```
这样就可以实现动态生成HTML表格,并通过添加和删除按钮添加或删除表格行。您可以根据需要调整代码以适应您的实际情况。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)