简体   繁体   English

如何在 javascript 中单击按钮删除数组值

[英]how to delete array value on button click in javascript

Here I am creating array of submitted data and save it into html tables.在这里,我正在创建提交数据数组并将其保存到 html 表中。 but now I also want to delete single row of data from same array on button click how can i do this但现在我还想在单击按钮时从同一数组中删除单行数据我该怎么做

Note: I want to delete it from array as well as from table注意:我想从数组和表中删除它

 var users = [] $(document).ready(loadTable); function loadTable() { for(var i = 0; i < users.length; i++){ for(var j = 0; j < users[i].length; j++){ //console.log(users[i][j]) } {continue;} } } $("#submit").on('click', function() { var temp = [document.getElementById("id").value,document.getElementById("name").value] users.push(temp) loadTable ($("tbody").append("<tr>" + "<td>" + $("#id").val() + "</td>" + "<td>" + $("#name").val() + "</td>" + "</tr>")); console.log(users) });
 table, th, td { border: 1px solid black; }
 <html> <head> <title>Hello</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> </head> <body> <input type="text" name="id" id="id"> <input type="text" name="name" id="name"> <button type="button" id="submit">Add</button> <table id="demo"> <tbody> </tbody> </table> </body> </html>

Use a combination of array.pop() and element.remove() to remove last element in the array and table if exists.使用array.pop()element.remove()的组合删除数组和表中的最后一个元素(如果存在)。

 var users = [] $(document).ready(loadTable); function loadTable() { for(var i = 0; i < users.length; i++){ for(var j = 0; j < users[i].length; j++){ //console.log(users[i][j]) } {continue;} } } $("#submit").on('click', function() { var temp = [document.getElementById("id").value,document.getElementById("name").value] users.push(temp) loadTable ($("tbody").append("<tr>" + "<td>" + $("#id").val() + "</td>" + "<td>" + $("#name").val() + "</td>" + "</tr>")); }); $("#delete").on('click',function(){ if(document.querySelectorAll('tbody > tr')){ document.querySelectorAll('tbody > tr')[document.querySelectorAll('tbody > tr').length -1].remove(); users.pop() console.log(users) } })
 table, th, td { border: 1px solid black; }
 <html> <head> <title>Hello</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> </head> <body> <input type="text" name="id" id="id"> <input type="text" name="name" id="name"> <button type="button" id="submit">Add</button> <button type='button' id='delete'>Delete</button> <table id="demo"> <tbody> </tbody> </table> </body> </html>

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

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