使用JS删除表中的行

时间:2016-09-15 12:16:41

标签: javascript jquery

我创建了一个在onclick事件后自动创建新行的表。此外,代码还会创建一个按钮,用于在单击行时删除这些行。

当我第二次点击“添加行onclick事件”时我无法解决的问题'我得到同一行的两份副本。

提前感谢任何人都可以帮助我,下面你可以找到代码:

function deleteRow(r) {
  var i = r.parentNode.parentNode.rowIndex;
  document.getElementById("orderedProductsTbl").deleteRow(i);
}

//this function manipulates DOM and displays content of our shopping cart
var shoppingCart = [];        
function displayShoppingCart(){
  var orderedProductsTblBody=document.getElementById("orderedProductsTblBody");
  //ensure we delete all previously added rows from ordered products table
  while(orderedProductsTblBody.rows.length>0) {
    orderedProductsTblBody.deleteRow(0);
  }

  //variable to hold total price of shopping cart
  var cart_total_price=0;
  //iterate over array of objects
  for(var product in shoppingCart){
    //add new row      
    var row=orderedProductsTblBody.insertRow();
    //add button
    var removeRow=document.createElement("Button");
    //set up button
    removeRow.innerHTML= "Delete"; 
    removeRow.setAttribute("onClick", "deleteRow(this)");                
    //create four cells for product properties 
    var cellName = row.insertCell(0);
    var cellDescription = row.insertCell(1);
    var cellPrice = row.insertCell(2);
    var cellDelete = row.insertCell(3);
    cellPrice.align="center";
    cellDescription.align ="right";
    cellDelete.align="right";
    cellName.height="40"
    cellPrice.height="40";
    cellDescription.height="40";
    cellDelete.height="40"
    //fill cells with values from current product object of our array
    cellName.innerHTML = shoppingCart[product].Name;
    cellDescription.innerHTML = shoppingCart[product].Description;
    cellPrice.innerHTML = shoppingCart[product].Price;
    cellDelete.appendChild( removeRow );
    cart_total_price+=shoppingCart[product].Price;     
  }
  //fill total cost of our shopping cart 
  document.getElementById("cart_total").innerHTML=cart_total_price;
}

function AddtoCart(name,description,price){
  //Below we create JavaScript Object that will hold three properties you have mentioned:    Name,Description and Price
  var singleProduct = {};
  //Fill the product object with data
  singleProduct.Name=name;
  singleProduct.Description=description;
  singleProduct.Price=price;
  //Add newly created product to our shopping cart 
  shoppingCart.push(singleProduct);
  //call display function to show on screen
  displayShoppingCart();
}

1 个答案:

答案 0 :(得分:0)

当您致电AddtoCart时,您会向元素shoppingCart添加元素,但删除行时只需删除DOM元素,但有关您的项目的信息仍在该数组中。

所以你必须将它从数组中删除:

function deleteRow(r) {
    var i = r.parentNode.parentNode.rowIndex;
    document.getElementById("orderedProductsTbl").deleteRow(i);
    shoppingCart.splice(i, 1); //http://stackoverflow.com/questions/5767325/how-to-remove-a-particular-element-from-an-array-in-javascript
}

修改

此修复程序不会帮助您解决每次添加相同产品的问题。因此,每次拨打shoppingCart或重写算法时都可以清除displayShoppingCart数组,以便不使用数组存储产品信息。