使用javascript添加表元素

时间:2016-09-23 05:11:40

标签: javascript html html-table elements

假设我有一个列产品表,评价这是其中的行

<tr>
    <td>pepsi</td>
    <td>2</td>
</tr>
<tr>
    <td>juice</td>
    <td>4</td>
</tr>

我想要总费率,例如:

<tr>
     <td>total</td>
     <td>6</td>
</tr>

3 个答案:

答案 0 :(得分:4)

获取表的所有最后一个td并通过迭代得到总和。最后,使用计算的总和生成tr

// variable for storing the sum
var sum = 0;
// get all last td from tr
// convert node list to array
// for old browser use `[].slice.call` instead
Array.from(document.querySelectorAll('tr td:last-child'))
  // iterate over the td elements
  .forEach(function(e) {
    // calculate the sum based on the content
    sum += Number(e.textContent) || 0;
  })

// create tr element
var tr = document.createElement('tr');
// add first cell for showing text
tr.insertCell(0).textContent = 'total';
// add second column for sowing the calculated sum
tr.insertCell(1).textContent = sum;

// get the table and append the generated tr element
document.querySelector('table tbody,table').appendChild(tr);
<table>
  <tr>
    <td>pepsi</td>
    <td>2</td>
  </tr>
  <tr>
    <td>juice</td>
    <td>4</td>
  </tr>
</table>

答案 1 :(得分:1)

您可以通过table.rows获取表格的所有行并循环显示,以获取如下所示的单元格值

(function(){
var table = document.getElementById("mytab1");
var sum = 0;
for (var i = 0, row; row = table.rows[i]; i++) {
  sum += parseInt(table.rows[i].cells[1].innerHTML)
  // cells[1] is hardcoded (Assumed <td>2</td> will always the second cell your row)
}

var tr = document.createElement('tr');
tr.insertCell(0).textContent = 'total';
tr.insertCell(1).textContent = sum;
table.appendChild(tr);
})();
<table id="mytab1">
  <tr>
      <td>pepsi</td>
      <td>2</td>
  </tr>
  <tr>
      <td>juice</td>
      <td>4</td>
  </tr>
</table>

答案 2 :(得分:0)

您可以使用Initialization , assignment ,declaration:

innerHTML