HTML+CSS+JS实现用户输入数据,表格展示数据
以下是一个简单的HTML、CSS和JavaScript代码示例,实现了用户输入数据后,这些数据被添加到表格中展示的功能。
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>User Input Table</title>
<style>
table {
width: 100%;
border-collapse: collapse;
}
table, th, td {
border: 1px solid black;
}
</style>
</head>
<body>
<table>
<thead>
<tr>
<th>Name</th>
<th>Age</th>
<th>Email</th>
</tr>
</thead>
<tbody id="data-table">
<!-- Data rows will be added here -->
</tbody>
</table>
<input type="text" id="name-input" placeholder="Name">
<input type="number" id="age-input" placeholder="Age">
<input type="email" id="email-input" placeholder="Email">
<button onclick="addData()">Add Data</button>
<script>
function addData() {
const name = document.getElementById('name-input').value;
const age = document.getElementById('age-input').value;
const email = document.getElementById('email-input').value;
const newRow = `<tr>
<td>${name}</td>
<td>${age}</td>
<td>${email}</td>
</tr>`;
document.getElementById('data-table').insertAdjacentHTML('beforeend', newRow);
// Clear the input fields after submission
document.getElementById('name-input').value = "";
document.getElementById('age-input').value = "";
document.getElementById('email-input').value = "";
}
</script>
</body>
</html>
CSS:
table {
width: 100%;
border-collapse: collapse;
}
table, th, td {
border: 1px solid black;
}
JavaScript:
function addData() {
const name = document.getElementById('name-input').value;
const age = document.getElementById('age-input').value;
const email = document.getElementById('email-input').value;
const newRow = `<tr>
<td>${name}</td>
<td>${age}</td>
<td>${email}</td>
</tr>`;
document.getElementById('data-table').insertAdjacentHTML('beforeend', newRow);
// Clear the input fields after submission
document.getElementById('name-input').value = "";
document.getElementById('age-input').value = "";
document.getElementById('email-input').value = "";
}
这段代码包含了一个表格用于展示数据,以及输入字段和一个按钮用于用户输入数据。当用户填写完毕并点击按钮后,数据将被添加到表格的底部,并且输入字段会被清空以便于新一轮的输入。
评论已关闭