【问题标题】:JS Array Splice to remove an element in an ArrayJS Array Splice 删除数组中的元素
【发布时间】:2014-07-30 00:32:25
【问题描述】:

我有一个表格,其中包含一个包含产品列表及其数量的数组,供客户下订单。在订单确认屏幕上,用户可以通过单击与特定row 关联的delete 按钮来删除订单中的项目。

这是我的HTML

<div id="summary">
    <table id="ordertable">
        <tr><th>Product</th>
        <th>Quantity</th>
        <th></th>
        </tr>
    </table>
</div>

这是我的JS

if($.cookie('order_cookie') != undefined){
    productArray = JSON.parse($.cookie('order_cookie'));
    $.cookie('order_cookie', JSON.stringify(productArray), { expires: 1, path: '/' });
}

var ordertable = document.getElementById("ordertable");

//Loop through the array
for(i = 0; i < productArray.length; i ++){
    item = productArray[i];
    var x = item.split(':');
    var row = ordertable.insertRow(1);
    var cell1 = row.insertCell(0);
    var cell2 = row.insertCell(1);
    var cell3 = row.insertCell(2);
    cell1.innerHTML = x[0];
    cell2.innerHTML = x[1];
    cell3.innerHTML = "<input type='button' value='Delete' class='deleteBtn'/>"
}

//Edit Function 
$(".editBtn").click(function(){
   console.log("Edit clicked");
});

//Delete Function
$(".deleteBtn").click(function(){
   console.log(productArray);
   var row = this.parentNode.parentNode;
   ordertable.deleteRow(row.rowIndex);//remove from the table
   productArray.splice(row.rowIndex);//remove from the order array
   console.log(productArray); 

});

//Confirm order Function
$(".confirmBtn").click(function(){
   console.log("Confirm clicked");
});

目前我可以成功地从表格中删除元素。但是,当我尝试从 array 中删除元素时,它会删除 array 的第一个元素

例如:

删除前的数组

["EXCEL 5LB BLACK:2", "EXCEL 5LB BLACK:3", "SATO WHITE LABEL:2", "SATO INK PADS:1", "SATO GUN:2"] 

单击删除时的数组

["EXCEL 5LB BLACK:2", "EXCEL 5LB BLACK:3", "SATO WHITE LABEL:2", "SATO INK PADS:1"] 

点击两次删除时的数组

["EXCEL 5LB BLACK:2", "EXCEL 5LB BLACK:3", "SATO WHITE LABEL:2"] 

第三次点击删除时的数组

["EXCEL 5LB BLACK:2", "EXCEL 5LB BLACK:3"] 

第四次点击删除时的数组

["EXCEL 5LB BLACK:2"] 

负责这个的代码是:

//Delete Function
$(".deleteBtn").click(function(){
   console.log(productArray);
   var row = this.parentNode.parentNode;
   ordertable.deleteRow(row.rowIndex);//remove from the table
   productArray.splice(row.rowIndex);//remove from the order array
   console.log(productArray); 

});

想法是要从表中删除的行与要从 array 中删除的项目相同 index,但目前这不起作用。

【问题讨论】:

    标签: javascript jquery arrays


    【解决方案1】:
    productArray.splice(row.rowIndex,1);
    

    使用这种拼接方法去除

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice

    只是一个建议:如果你使用ng-repeat of angular.js,你不必担心在表和数组中都删除

    【讨论】:

      【解决方案2】:

      您忘记了 howMany 参数。这就是要从数组中删除的数量。

      array.splice(index , howMany)
      

      所以你的代码应该是这样的

      productArray.splice(row.rowIndex, 1);
      

      https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice

      【讨论】:

      • 当我这样做时,无论我做什么,它仍然会删除数组的第一个元素。例如,如果我单击表格第 4 行,我希望从数组中删除第 4 个元素,但事实并非如此。它删除了第一个
      【解决方案3】:
      const candidates = [
        {
          name: "Amir",
          lastName: "Hoxha",
          email: "wow@gmail.com",
          phone: 198465,
        },
        {
          name: "geogre",
          lastName: "horhe",
          email: "Horhe@masvidal.com",
          phone: 694204,
        },
        {
          name: "Ali",
          lastName: "Hamdi",
          email: "Dragashi123@gmail.com",
          phone: 454784,
        },
      ];
      const name = document.getElementById("name").value;
      const lastName = document.getElementById("last-name").value;
      const email = document.getElementById("email").value;
      const phone = document.getElementById("phone").value;
      
      bulidTable(candidates);
      
      function bulidTable(data) {
        let myTable = document
          .getElementById("my-table")
          .getElementsByTagName("tbody")[0];
      
        myTable.innerHTML = "";
      
        for (let i = 0; i < data.length; i++) {
          var row = `<tr>
                          <td>${data[i].name}</td>
                          <td>${data[i].lastName}</td>
                          <td>${data[i].email}</td>
                          <td>${data[i].phone}</td>
                          <td><button id="btnDelete" >Delete</button>
                             <button id="btnEdit" onclick="editRow()">Edit</button>
                          </td>
                       </tr> `;
          myTable.innerHTML += row;
        }
      }
      
      const myTable = document
        .getElementById("my-table")
        .getElementsByTagName("tbody")[0];
      
      function addRow() {
        // changeToAdd();
        if (!valditade()) {
          const name = document.getElementById("name").value;
          const lastName = document.getElementById("last-name").value;
          const email = document.getElementById("email").value;
          const phone = document.getElementById("phone").value;
          console.log(name, lastName, email, phone);
      
          const obj = {
            name: name,
            lastName: lastName,
            email: email,
            phone: phone,
          };
      
          candidates.push(obj);
      
          valditade();
      
          bulidTable(candidates);
        }
      }
      
      // const btnEdit = document.getElementById("btnEdit");
      // console.log(btnEdit);
      // The Delete Row function
      addEventListener("click", (e) => {
        if (e.target.id === "btnDelete") {
          console.log(e.target.parentElement.parentElement);
          const indexToRemove = e.target.parentElement.parentElement.rowIndex - 1;
          candidates.splice(indexToRemove, 1);
        }
        bulidTable(candidates);
      });
      
      // The Edit Row function
      
      const btnEdit = document.getElementById("my-button");
      console.log(btnEdit);
      const btnSave = document.getElementById("btnSave");
      console.log(btnSave);
      
      var table = document.getElementById("my-table");
      var rIndex;
      function editRow() {
        for (var i = 1; i < table.rows.length; i++) {
          table.rows[i].onclick = function () {
            rIndex = this.rowIndex;
            console.log(rIndex);
      
            document.getElementById("name").value = this.cells[0].innerHTML;
            document.getElementById("last-name").value = this.cells[1].innerHTML;
            document.getElementById("email").value = this.cells[2].innerHTML;
            document.getElementById("phone").value = this.cells[3].innerHTML;
          };
      
          document.getElementById("my-button").style.display = "none";
          document.getElementById("btnSave").style.display = "block";
        }
      }
      
      btnSave.addEventListener("click", (event) => {
        console.log(rIndex);
        console.log(candidates);
      
        const name = document.getElementById("name").value;
        const lastName = document.getElementById("last-name").value;
        const email = document.getElementById("email").value;
        const phone = document.getElementById("phone").value;
      
        for (var i = 0; i < candidates.length; i++) {
          if (i === rIndex - 1) {
            candidates[i].name = name;
            candidates[i].lastName = lastName;
            candidates[i].email = email;
            candidates[i].phone = phone;
          }
        }
      
        event.preventDefault();
        document.getElementById("my-button").style.display = "block";
        document.getElementById("btnSave").style.display = "none";
      
        console.log(name, lastName, email, phone);
        bulidTable(candidates);
      });
      
      // Function for clearing the inputs after the add button was clicked on
      
      let btnClear = document.getElementById("my-button");
      let inputs = document.querySelectorAll("input");
      
      btnClear.addEventListener("click", () => {
        inputs.forEach((input) => (input.value = ""));
      });
      
      btnSave.addEventListener("click", () => {
        inputs.forEach((input) => (input.value = ""));
      });
      
      //This function makes sure that the user has enterted all the required information.
      function valditade() {
        var isEmpty = false;
        const name = document.getElementById("name").value;
        const lastName = document.getElementById("last-name").value;
        const email = document.getElementById("email").value;
        const phone = document.getElementById("phone").value;
      
        if (name === "" && lastName === "" && email === "" && phone === "") {
          alert("You Left all the inputs empty");
          isEmpty = true;
        } else if (name === "") {
          alert("Please provide your name");
          isEmpty = true;
        } else if (lastName === "") {
          alert("Please Provide your last name");
          isEmpty = true;
        } else if (email === "") {
          alert("Please provide your Email");
          isEmpty = true;
        } else if (phone === "") {
          alert("Please provide your Phone number");
          isEmpty = true;
        }
        return isEmpty;
      }
      
      body {
        background: linear-gradient(to left, #333, #333 50%, #eee 75%, #333 75%);
      }
      table,
      th,
      td {
        font-family: Georgia, "Times New Roman", Times, serif;
      
      }
      
      table#my-table {
        border: 1px solid black;
        border-radius: 14px;
        border-spacing: 0;
      }
      table#my-table td,
      table#my-table {
        border-bottom: 1px solid black;
        padding: 10px;
      }
      #table {
        margin: 5rem 31rem;
        color: white;
        font-size: 18px;
      
      }
      
      /* #my-table tr:nth-child(even){
      
      } */
      /* #my-table{
        border: 1px solid black;
        position: static;
        width: 20%;
      } */
      
      table#my-table tr:last-child > td {
        border-bottom: none;
      }
      #my-button {
        display: block;
        background-color: #b00b69;
        padding: 12px;
        font-size: 14px;
        color: white;
      }
      .btnSave{
        display: flex;
        justify-content: center;
        margin: 20px;
        padding-top: 15px;
      }
      #btnSave{
        display: none;
        background-color: #b00b69;
        padding: 12px;
        font-size: 14px;
        color: white;
      }
      #my-form {
        display: flex;
        justify-content: center;
        margin: 20px;
        padding-top: 15px;
      }
      #name,
      #last-name,
      #email,
      #phone {
        margin: 5px;
        padding: 6px;
        border-radius: 5px;
        font-size: 14px;
      }
      #name:focus {
        background-color: #b00b69;
      }
      #last-name:focus {
        background-color: #b00b69;
      }
      #email:focus {
        background-color: #b00b69;
      }
      #phone:focus {
        background-color: #b00b69;
      }
      #btnDelete {
        color: white;
        background-color: black;
        padding: 8px;
        padding-right: 10px;
        margin-top: 5px;
      }
      #btnEdit {
        color: white;
        background-color: black;
        padding: 8px;
        padding-right: 25px;
        margin-top: 5px;
      }
      
      <!DOCTYPE html>
      <html lang="en">
          <body>
      <head>
          <meta charset="UTF-8">
          <meta http-equiv="X-UA-Compatible" content="IE=edge">
          <meta name="viewport" content="width=device-width, initial-scale=1.0">
          <title>Table </title>
          <link rel="styleSheet" href="style.css">
          <script src="table.js" defer></script>
      </head>
      <body>
      
          <form  id="my-form">
              <input type="text"  id="name"   required maxlength="8">
              <input type="text" id="last-name" required maxlength="8">
              <input type="text" id="email"   required maxlength="23" >
              <input type="number" id="phone" pattern="/^-?\d+\.?\d*$/" 
              onKeyPress="if(this.value.length == 9) return false;">
              <button id="my-button" onclick="addRow()"  value="Add">Add</button>
              <button id="btnSave">Save</button>
          </form>
      
      
       <div id="table">
          <table id="my-table">
             <thead> 
              <tr>
                  <th>Name</th>
                  <th>Last Name</th>
                  <th>Email</th>
                  <th>phone</th>
                  <th>Action</th>
              </tr> 
              </thead>
              <tbody id="my-body">
          
               </tbody>
               </table>
       
      </body>
      </html>
      

      **这是一个使用对象数组填充的表,我使用 push() 方法向表中添加新行,并使用 splice method() 删除行**

      【讨论】:

      • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center。
      猜你喜欢
      • 1970-01-01
      • 2021-09-23
      • 2021-04-19
      • 1970-01-01
      • 2021-03-02
      • 2021-05-04
      • 1970-01-01
      • 2019-07-01
      • 2022-08-03
      相关资源
      最近更新 更多