繁体   English   中英

使用innerHTML更新表格单元时出错

[英]Error updating table cell using innerHTML

我有一个表,显示订单项列表。 row包含3个按钮,以将订单数量减少1,将订单数量增加1,并从订单中删除整个项目。 我遇到一个奇怪的问题,即当我减少特定行的订单数量时,它将导致存储在第二行中的值被更新...

这是我设置表格的地方:

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

//Reference to the order table
var ordertable = document.getElementById("ordertable");

    //Loop through the Array and display in the table
    for(var i = 0; i < productArray.length; i ++){
       // console.log(productArray[i]);
        console.log("Order Item " + i);
        console.log("StockCode: " + productArray[i].stockCode);
        console.log("Quantity: " + productArray[i].quantity);

        var row = ordertable.insertRow(i + 1);
        var cell1 = row.insertCell(0);
        var cell2 = row.insertCell(1);
        var cell3 = row.insertCell(2);
        cell1.innerHTML = productArray[i].stockCode;
        cell2.innerHTML = productArray[i].quantity;
        cell3.innerHTML = "<input type='button' value='-' class='removeBtn'/><input type='button' value='+' class='addBtn'/><input type='button' value='Delete' class='deleteBtn'/>"
    }

这是我减少表中商品的订购数量的地方

//Change the total 
$('.removeBtn').click(function(){ //Remove 1 from quantity

    console.log(productArray);
    console.log("remove");
    var row = this.parentNode.parentNode;
    console.log(row);
    console.log(row.rowIndex);
    var elementToUpdate = row.rowIndex - 1;
    productArray[elementToUpdate].quantity--;
    cell2.innerHTML = productArray[elementToUpdate].quantity;
   // $.cookie('order_cookie', JSON.stringify(productArray), { expires: 1, path: '/' });
});

谁能阐明为什么会这样? 我认为这可能与我使用Javascript而不是HTML生成表的事实有关,但我不确定。

非常感谢您的帮助

使用event Delegation 您动态添加.removeBtn

$("#ordertable").on("click" , ".removeBtn" , function(){ 

      // your code come here
});

暂无
暂无

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

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