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

Javascript 使用innerHTML更新表单元格时出错,javascript,jquery,innerhtml,Javascript,Jquery,Innerhtml,我有一张表格,上面显示了订单项目的列表。每行包含3个按钮,用于将订单数量减少1,将订单数量增加1,并从订单中删除整个项目。我有一个奇怪的问题,当我减少某一行的订单数量时,它会导致存储在第二行中的值被更新 这是我设置表格的地方: if($.cookie('order_cookie') != undefined){ productArray = JSON.parse($.cookie('order_cookie')); $.cookie('order_cookie', JSON.st

我有一张表格,上面显示了订单项目的列表。每行<代码>包含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'/>"
    }
有人能解释一下为什么会发生这种情况吗?我认为这可能与我使用
Javascript
而不是
HTML
生成表这一事实有关,但我不能完全确定


非常感谢您的帮助

使用
事件委派
。您可以动态添加
.removeBtn

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

      // your code come here
});

如果可以的话,请设置一个JSFIDLE来演示您的问题。您能显示您的HTML吗?最好将事件绑定到表中,而不是直接绑定到每个按钮。`将事件绑定到表中,而不是直接绑定到每个按钮'…什么?@Garzun那么您还必须提到sudharsan应该将此代码放入
doc ready
否则,如果将其放在外部,这将不起作用,而委托给
$(文档)
不需要doc ready块。因为doc在dom就绪之前就已经存在了。@Garzun没错,但是异步调用和sudarshan解决的这个问题呢。创建新的dom条目并将事件绑定到它。@Jai surdarshan已经修改了他的答案,所以他正在做我提到的事情。顺便说一句:我不是落选者
$("#ordertable").on("click" , ".removeBtn" , function(){ 

      // your code come here
});