Javascript在表的最后一行之前向表中添加行

时间:2017-08-29 11:16:39

标签: javascript html-table

我的表格代码是:

这是我的JSfiddle

function insert_Row() {
  var xTable = document.getElementById('partsTable');
  var tr = document.createElement('tr');
  tr.innerHTML = "<td colspan=2><input type='text' name='parts[]' placeholder='part 1' class='form-control' > </td><td><input type='text' name='price[]' placeholder='price e.g 100' class='form-control' ></td>";
  xTable.appendChild(tr);
}
<table class="table table-bordered table-striped" id="partsTable">
  <thead>
    <tr class="bg-primary">
      <th colspan=2>Services</th>
      <th>Amount</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td colspan=2><input type='text' name="parts[]" placeholder="part 1" class='form-control'> </td>
      <td><input type='text' name="price[]" placeholder="price e.g 100" class='form-control'></td>
    </tr>
    <tr>
      <td colspan=3><button onclick="insert_Row();">+</button></td>

    </tr>
  </tbody>
  <tfoot>
    <tr>
      <td class="col-md-6"> &nbsp </td>
      <td><strong>Total</strong></td>
      <td><strong>$1000.00</strong></td>
    </tr>
  </tfoot>
</table>

但它在tr末尾添加了新的tbody。我想在tr之前添加tr一个地方。这可能吗?

2 个答案:

答案 0 :(得分:1)

specific method用于在指定索引的表中创建和插入行:

function insert_Row()
{
    var xTable = document.getElementById('partsTable');
    var index = xTable.rows.length - 1;
    var tr = xTable.insertRow(index);
    tr.innerHTML = "<td colspan=2><input type='text' name='parts[]' placeholder='part 1' class='form-control' > </td><td><input type='text' name='price[]' placeholder='price e.g 100' class='form-control' ></td>" ;
}

答案 1 :(得分:0)

您可以找到要插入新行的行。并使用insertAdjacentHTML beforebegin前置或beforeend追加

function insert_Row(button)
{
    var xTable=document.getElementById('partsTable');
    var body = xTable.tBodies[0]
    var rows = body.rows
    
    // pick the last and prepend
    rows[rows.length - 1].insertAdjacentHTML('beforebegin', "<tr><td colspan=2><input type='text' name='parts[]' placeholder='part 1' class='form-control' > </td><td><input type='text' name='price[]' placeholder='price e.g 100' class='form-control' ></td></tr>")
}
<table class="table table-bordered table-striped" id="partsTable">
    <thead>
        <tr class="bg-primary" >
            <th colspan=2>Services</th>
            <th>Amount</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td colspan=2><input type='text' name="parts[]" placeholder="part 1" class='form-control' > </td>
            <td><input type='text' name="price[]" placeholder="price e.g 100" class='form-control' ></td>
        </tr>
        <tr>
            <td colspan=3><button onclick="insert_Row();">+</button></td>

        </tr>
    </tbody>
    <tfoot>
        <tr>
                <td class="col-md-6"> &nbsp </td>
                <td><strong>Total</strong></td>
                <td><strong>$1000.00</strong></td>
        </tr>
    </tfoot>
</table>