简体   繁体   English

JS Array Splice 删除数组中的元素

[英]JS Array Splice to remove an element in an Array

I have a table being populated by an array containing a list of products and their quantities for an order to be placed by a customer.我有一个由数组填充的表,其中包含产品列表及其数量,供客户下订单。 On the Order confirmation screen the user can remove items in the order by clicking the delete button associated with the particular row .在订单确认屏幕上,用户可以通过单击与特定row关联的delete按钮来删除订单中的项目。

This is my HTML这是我的HTML

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

This is my JS这是我的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");
});

Currently I can successfully remove elements from the table.目前我可以成功地从表中删除元素。 However when I try to remove the element from the array it removes the first element of the array但是,当我尝试从array中删除元素时,它会删除array的第一个元素

For example:例如:

Array before delete删除前的数组

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

Array when delete is clicked once单击一次删除时的数组

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

Array when delete is clicked twice单击两次删除时的数组

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

Array when delete is clicked third time第三次点击删除时的数组

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

Array when delete is clicked fourth time第四次点击删除时的数组

["EXCEL 5LB BLACK:2"] 

The code responsible for this is:负责此的代码是:

//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); 

});

The idea is that the row to be removed from table is the same index as item to be removed from array but this is not working at the moment.这个想法是要从表中删除的行与要从array中删除的项目的index相同,但这目前不起作用。

productArray.splice(row.rowIndex,1);

use this splice method to remove 使用此拼接方法删除

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

Just a suggestion: You don't need to worry about deleting both in the table and in the array if you use ng-repeat of angular.js 只是一个建议:如果您使用angular.js的 ng-repeat ,则不必担心在表和数组中都将其删除

You forgot the howMany argument. 您忘记了howMany参数。 That's how many to remove from the array. 那就是要从阵列中删除的数量。

array.splice(index , howMany)

So your code should look like 所以你的代码应该看起来像

productArray.splice(row.rowIndex, 1);

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

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>

**This is a table that is populated using an array of objects and i add new rows to the table using the push() method and i removed rows using the splice method() ** **这是一个使用对象数组填充的表,我使用 push() 方法向表中添加新行,并使用 splice 方法() 删除行 **

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

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