如何在表中添加2行或更多行

时间:2016-02-14 10:04:44

标签: javascript html

我有3行,同一个表中有3个按钮,我试图添加彼此独立的新行。但是当我点击第二个或第三个按钮时它会输出第一行 这是第一个按钮和第二个按钮的javascript代码。

--path=...

这里有一些html

function addRow(dataTable, id) {
  var table = document.getElementById('dataTable');
  var rowCount = table.rows.length;
  var row = table.insertRow(3);
  var colCount = table.rows[5].cells.length;
  for (var i = 0; i < colCount; i++) {
    var newcell = row.insertCell(i);
    newcell.innerHTML = table.rows[4].cells[i].innerHTML;
    document.getElementById("agri").style.visibility = "hidden"; // remove button from newly added row
  }
  document.getElementById("agri").style.visibility = "visible";
}

function addRow1(dataTable, id) {
  var table = document.getElementById('dataTable');
  var rowCount = table.rows.length;
  var row = table.insertRow(4);
  var colCount = table.rows[6].cells.length;
  for (var i = 0; i < colCount; i++) {
    var newcell = row.insertCell(i);
    newcell.innerHTML = table.rows[5].cells[i].innerHTML;
    document.getElementById("promotion").style.visibility = "hidden";  // remove button from newly added row
  }
  document.getElementById("promotion").style.visibility = "visible";
}

请帮助
谢谢

3 个答案:

答案 0 :(得分:0)

您有错误

 var table = document.getElementById('dataTable');

但是,因为我认为你使用dataTable作为变量而不是字符串

var table = document.getElementById(dataTable);

还将您的html代码与表

放在一起

答案 1 :(得分:0)

如何添加row属性并根据元素编号

更改其值

答案 2 :(得分:0)

   <script>
  var ii=0;
   function addRow(dataTable, id, type) {
   ii++       
   console.log(id);

     var table = document.getElementById(dataTable);

     var row = table.insertRow(id+parseInt(type));
     var colCount = table.rows[id].cells.length;

     for (var i = 0; i < colCount; i++) {
       var newcell = row.insertCell(i);
       newcell.innerHTML = table.rows[id].cells[i].innerHTML;

   table.rows[id].cells[i].querySelector('input').value=ii.toString();

   if(type==1) 
   table.rows[id].cells[i].style.backgroundColor='red';      
   else
   table.rows[id].cells[i].style.backgroundColor='blue';

     }

   }

   </script>

   <table id="dataTable">
   <tr>1
   <td><input type="button" id="agri" value="Add Row after" onclick="addRow('dataTable',this.parentNode.parentNode.rowIndex,'1')" /></td>
   <td><input type="button" id="agri2" value="Add Row before" onclick="addRow('dataTable',this.parentNode.parentNode.rowIndex,'-1')" /></td>

   </tr>

   </table>
相关问题