JS Array Splice删除Array中的元素

时间:2014-06-09 12:54:06

标签: javascript jquery arrays

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

这是我的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); 

});

我们的想法是,要从表中删除的行与要从index中删除的项目array相同,但目前无效。

2 个答案:

答案 0 :(得分:1)

productArray.splice(row.rowIndex,1);

使用此拼接方法删除

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

只是一个建议:如果您使用ng-repeatangular.js

,则无需担心在表格和数组中同时删除它们

答案 1 :(得分:0)

您忘记了howMany参数。这是从阵列中删除的数量。

array.splice(index , howMany)

所以你的代码应该是

productArray.splice(row.rowIndex, 1);

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

相关问题