js 根据data动态生成table表格,每行后面有一个删除按钮,这个删除按钮怎么绑定事件,并且可以在点击时获取当前行的索引值?

山楂片
  • 358
var tablePlugin = {
  tableDate: [],
  initTable:function(){
    var tableTbody = document.getElementById('tableTbody');
    var tr = this.tableTrModule(this.tableDate);
    console.log(tr);
    tableTbody.innerHTML = tr;
  },
  tableTrModule:function(data){
    var dataLen = data.length;
    var tr = "";
    if (dataLen == 0){
      tr = "<td>暂无内容</td>";
    } else{
      for(var i =0;i<data.length;i++){
        tr += "<tr><td>"+data[i].No+"</td><td>"+data[i].name+"</td><td>"+data[i].sex+"</td><td>"+data[i].achievement+"</td><td><input type='button' value='删除' onclick='deleteRow("+i+")'/></td></tr>"
      }
    }
    return tr;
  },
  addRow:function(){
    console.log('新增')
  },
  deleteRow:function(index){
    console.log(index);
  }
}
回复
阅读 1.8k
2 个回答
yuanxiaowa
  • 10.1k
var tablePlugin = {
  tableDate: [],
  initTable:function(){
    var tableTbody = document.getElementById('tableTbody');
    var tr = this.tableTrModule(this.tableDate);
    console.log(tr);
    tableTbody.addEventListener('click', function(e) {
        if (e.target.tagName === 'INPUT') {
            var tr = e.target.parentNode.parentNode
            var index = [...tr.parentNode.childNodes].indexOf(tr)
            console.log(index)
        }
    })
    tableTbody.innerHTML = tr;
  },
  tableTrModule:function(data){
    var dataLen = data.length;
    var tr = "";
    if (dataLen == 0){
      tr = "<td>暂无内容</td>";
    } else{
      for(var i =0;i<data.length;i++){
        tr += "<tr><td>"+data[i].No+"</td><td>"+data[i].name+"</td><td>"+data[i].sex+"</td><td>"+data[i].achievement+"</td><td><input type='button' value='删除'/></td></tr>"
      }
    }
    return tr;
  },
  addRow:function(){
    console.log('新增')
  },
  deleteRow:function(index){
    console.log(index);
  }
}

把你的deleteRow方法定义到全局

function deleteRow(index){

console.log(index);

}

宣传栏