简体   繁体   English

function 从表中删除最后一个元素

[英]function that removes last element from table

I have this code that adds input to table.我有这段代码可以将输入添加到表中。 I want to make a function that removes the last added row in the table.我想做一个 function 删除表中最后添加的行。
Here is the code that I have:这是我拥有的代码:

 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>

For example if I enter more rows in my table and if I click on my remove button it will remove the last element that was entered in the table.例如,如果我在表格中输入更多行并且单击删除按钮,它将删除表格中输入的最后一个元素。

Use .lastElementChild property to remove the last added tr tag in the table使用.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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM