【问题标题】:How to delete an object from array on Button click?如何在按钮单击时从数组中删除对象?
【发布时间】:2019-10-29 10:06:58
【问题描述】:

我正在尝试执行静态粗略操作。当用户在文本框上添加详细信息时,它将存储在对象数组中,然后该对象打印在表格上。现在我想通过数组中的删除按钮删除行。我试过.splice(),但它不起作用。数据正在从表中删除,但我想从数组中删除它。我在下面提供我的页面:

<!doctype html>
<html>

<head>
  <meta charset="utf-8">
  <title>Table With Bootstrap</title>
  <link rel="stylesheet" href="bootstrap.min.css">
</head>

<body><br><br><br>
  <div class="container">
    <h1 align="center">Enter Details</h1><br>
    <div class="row">
      <div class="col-sm-4">
        <!--style="border:solid"-->
        <div>
          <label>Enter ID: </label><br>
          <input type="number" class="form-control" id="id" name="id" required/>

          <label>Enter Name: </label><br>
          <input type="text" class="form-control" id="name" name="name" required/>

          <label>Enter City: </label><br>
          <input type="text" class="form-control" id="city" name="city" required />

          <label>Enter Email: </label><br>
          <input type="email" class="form-control" id="email" name="email" required/><br>

          <button class="btn btn-success" onClick="printTable();">Submit</button> <button class="btn btn-danger" onClick="resetTable();">Reset Table</button></div>
      </div>
      <div class="col=sm-4">
        <h1 style="color: white">Hello World heyy</h1>
      </div>
      <div class="col-sm-4" style="float: right;">
        <table class="table table-sm table-striped table-hover  table-bordered" style="border-radius: 5px;">
          <thead class="thead-dark">
            <tr>
              <th>User ID</th>
              <th>User Name</th>
              <th>User Email</th>
              <th>User City</th>
              <th>User Delete</th>
            </tr>
          </thead>
          <tbody id="showResult">

          </tbody>
        </table>
      </div>
    </div>
  </div>
  <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
  <script>
    let data = [];

    function resetTable() {
      const confirmMessage = confirm("Are you sure want to reset table data? It will delete all data from table. You cannot undo this action.!");
      if (confirmMessage) {
        window.location.reload();
        alert("Table Data Cleared Successfully");
      } else {
        alert("cancelled.!");
      }
    }

    function printTable() {
      const getId = document.getElementById("id").value;
      const getName = document.getElementById("name").value;
      const getCity = document.getElementById("city").value;
      const getEmail = document.getElementById("email").value;

      if (getId != '', getName != '', getCity != '', getEmail != '') {

        const obj = {
          id: getId,
          name: getName,
          city: getCity,
          email: getEmail
        }
        data.push(obj);
        print(data);
        $('#id').val("");
        $('#name').val("");
        $('#city').val("");
        $('#email').val("");
      } else {
        alert("All feilds are Mandatory..");
      }
    }

    function print(data) {

      let result = '';

      for (let i = 0; i < data.length; i++) {

        result += `

<tr id='row'>
<td>${data[i].id}</td>
<td>${data[i].name}</td>
<td>${data[i].email}</td>
<td>${data[i].city}</td>
<td><input type='button' onclick='deleteRow(this);' class='btn btn-danger' value='Delete'/></td>
</tr>`;
        document.getElementById('showResult').innerHTML = result;
      }
    }

    function deleteRow(btn) {
      var cnfrmMessage = confirm("Are you sure want to Delete selected data? You cannot undo this action.");
      if (cnfrmMessage == true) {
        var row = btn.parentNode.parentNode;
        row.parentNode.removeChild(row);


      } else {
        alert("Cancelled..!!");
      }
    }
  </script>


</body>

</html>

【问题讨论】:

    标签: javascript jquery arrays object


    【解决方案1】:

    我想你忘记更新你的数据数组了。 将您的 deleteRow 函数更改为

    function deleteRow(btn) {
    var cnfrmMessage = confirm("Are you sure want to Delete selected data? You cannot undo this action.");
    if(cnfrmMessage == true){
        var row = btn.parentNode.parentNode;
        row.parentNode.removeChild(row);
        // update your data (remove item by row id)
        data = data.filter((item)=>item.id!==$(row).children()[0].innerText);
    }
    else{
        alert("Cancelled..!!");
    }
    }
    

    您的数组实际上是一个“数据”。所以你需要一个唯一的 id 来删除特定的行或对此做一些事情。 其他方式,您可以比较要删除的行中的所有字段,但这不是一个好的解决方案。

    【讨论】:

    • @MuhammadHassaan 这基本上就是我试图用文字解释的内容......这个网站并不是真正用于复制粘贴工作代码或家庭作业。这是为了解释解决方案
    • 是的.. 你能告诉我如何使用 .slice(); 执行此任务吗? ?
    • 您可以尝试事件委托来获取要删除的索引当前元素并使用 .slice 在没有该索引的情况下进行切片
    【解决方案2】:

    您需要一种方法来识别列表中脱离 HTML 元素的项目。看起来您可以使用 id 列(尽管通常将类似的内容放在属性中会更好)。然后你可以使用过滤器:

    将 id 添加到 deleteRow 函数中。

    deleteRow(this, ${data[i].id})
    
    // Removes item with id.
    var a = [
        {id:1},
        {id:2},
        {id:3},
        {id:4},
        {id:5},
        {id:6},
        {id:7},
        {id:8},
        {id:9}
    ];
    
    a.filter(item => item.id != deleteId);
    

    【讨论】:

    • 如果我这样做,我只能删除唯一的 id 为 3 的行 .. 我想删除用户按下删除按钮的行,如代码所示。
    • @MuhammadHassaan 就像我说的,从 HTML 元素中获取 id。但是你也可以将 id 添加到 deleteRow 函数中。
    猜你喜欢
    • 2021-02-06
    • 2021-09-19
    • 1970-01-01
    • 2022-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-13
    • 1970-01-01
    相关资源
    最近更新 更多