javascript - 将按钮添加到动态生成的 HTML 表格中

标签 javascript html html-table

我正在尝试使用 JavaScript 为动态生成的 HTML 表的每一行添加一个按钮。这是我的代码:

// helper function        
function addCell(tr, text) {
    var td = tr.insertCell();
    td.innerHTML = text;
    return td;
}

// insert data
list.forEach(function (item) {
    var row = table.insertRow();
    var button = document.createElement('button'); 
    var bText = document.createTextNode('View'); 
    button.appendChild(bText); 
    addCell(row, item.itemName);
    addCell(row, '$ ' + item.total.toFixed(2));
    addCell(row, button);
});

我设法打印出除按钮之外的所有其他字段。按钮的列只是简单地打印出:

[object HTMLButtonElement]

只是想知道是否有办法将图像按钮添加到动态生成的表格中?选择按钮后,我想获取该行的值并将其作为参数传递给另一个函数。

最佳答案

Here the fiddle 。你想要什么我不知道。这样你就可以到达终点线。

var previousitem=null;
function removeRowbyItem(item) {
      item.parentElement.parentElement.style.backgroundColor="red";
      if(previousitem!=null){
         previousitem.style.backgroundColor="";
         console.log(previousitem);
      }
    previousitem=item.parentElement.parentElement;
}
removeRow.innerHTML = "click me";
removeRow.onclick = function() {
  removeRowbyItem(this);
};

关于javascript - 将按钮添加到动态生成的 HTML 表格中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47806846/

相关文章:

javascript - 为什么我得到的 position() 左值异常高?

html - 选择框的高度在 ie7 问题中增长

jquery - 在 HTML 表格布局中重新定位列及其内容

javascript - Yii2 的 jQuery 倒计时小部件的俄语复数

javascript - 使进度条响应

javascript - 我可以在 Angular Js 中使用哪些东西

javascript - 在具有给定目标宽度/高度的 Canvas 上绘制 Canvas 会导致图像扭曲

javascript - 检测 html 5 Canvas 上的点击与拖动

html - 表 : How to make Firefox act same like IE 中的图像

excel - 复杂表的 rowspan 和 colspan