我有這段代碼可以將輸入添加到表中。我想創建一個函式來洗掉表中最后添加的行。
這是我擁有的代碼:
function add() {
var name = document.getElementById("name");
var surname = document.getElementById("surname");
var output = document.getElementById("output");
name = name.value;
surname = surname.value;
output.innerHTML = "<tr><td>" name "</td><td>" surname "</td></tr>"
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial- scale=1.0">
<title>Document</title>
<style>
table,
td {
border: 1px solid black;
border-collapse: collapse;
}
</style>
</head>
<body>
<form action="">
<div>
<label for="name">Name</label>
<input type="text" id="name">
</div>
<div>
<label for="name">Surname</label>
<input type="text" id="surname">
</div>
</form>
<input type="button" onclick="add();" value="Add">
<input type="button" onclick="remove();" value="Remove">
<div>
<table id="output">
<thead>
<td>Name</td>
<td>Surname</td>
</thead>
<tbody></tbody>
</table>
</div>
</body>
</html>
例如,如果我在表格中輸入更多行,并且如果我單擊洗掉按鈕,它將洗掉表格中輸入的最后一個元素。
uj5u.com熱心網友回復:
使用.lastElementChild屬性洗掉tr表格中最后添加的標簽
function add() {
var name = document.getElementById("name");
var surname = document.getElementById("surname");
var output = document.getElementById("output");
name = name.value;
surname = surname.value;
output.innerHTML = "<tr><td>" name "</td><td>" surname "</td></tr>"
}
function remove() {
var output = document.getElementById("output");
output.lastElementChild.remove();
}
table,
td {
border: 1px solid black;
border-collapse: collapse;
}
<form action="">
<div>
<label for="name">Name</label>
<input type="text" id="name">
</div>
<div>
<label for="name">Surname</label>
<input type="text" id="surname">
</div>
</form>
<input type="button" onclick="add();" value="Add">
<input type="button" onclick="remove();" value="Remove">
<div>
<table id="output">
<thead>
<td>Name</td>
<td>Surname</td>
</thead>
<tbody></tbody>
</table>
</div>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/362144.html
標籤:javascript html 功能
下一篇:為什么我不能用`varoutput=document.getElementById('message').innerHTML;`做一個回圈
