建立一个完整的html代码要求如下:包含一个有5列的表格宽度为500px可以通过点击表格上方的按钮将表单的数据添加到表格中也可以通过点击表格第一列中的数据来删除一整行数据表格初始带有两条数据
<!DOCTYPE html>
<html>
<head>
<title>Table with Adding and Deleting Rows</title>
<style>
table{
width: 500px;
border-collapse: collapse;
}
table, th, td{
border: 1px solid black;
}
th{
background-color: #ddd;
}
td, th{
padding: 10px;
text-align: center;
}
button{
margin: 10px 0;
padding: 10px;
background-color: #4CAF50;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
}
</style>
</head>
<body>
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Age</th>
<th>City</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>John Doe</td>
<td>30</td>
<td>New York</td>
<td><button onclick="deleteRow(this)">Delete</button></td>
</tr>
<tr>
<td>2</td>
<td>Jane Doe</td>
<td>25</td>
<td>London</td>
<td><button onclick="deleteRow(this)">Delete</button></td>
</tr>
</tbody>
</table>
<button onclick="addRow()">Add Row</button>
<pre><code><script>
function addRow(){
var table = document.getElementsByTagName('table')[0];
var newRow = table.insertRow(-1);
var idCell = newRow.insertCell(0);
var nameCell = newRow.insertCell(1);
var ageCell = newRow.insertCell(2);
var cityCell = newRow.insertCell(3);
var actionCell = newRow.insertCell(4);
idCell.innerHTML = table.rows.length - 1;
nameCell.innerHTML = 'New Person';
ageCell.innerHTML = 0;
cityCell.innerHTML = 'Unknown';
actionCell.innerHTML = '<button onclick="deleteRow(this)">Delete</button>';
}
function deleteRow(btn){
var row = btn.parentNode.parentNode;
row.parentNode.removeChild(row);
// Update ID column for remaining rows
var table = document.getElementsByTagName('table')[0];
var rows = table.rows;
for(var i=1; i<rows.length; i++){
rows[i].cells[0].innerHTML = i;
}
}
</script>
</code></pre>
</body>
</html
原文地址: https://www.cveoy.top/t/topic/hbIJ 著作权归作者所有。请勿转载和采集!