添加具有特定行类的行

时间:2018-12-01 15:45:34

标签: javascript jquery html

我有2个列和1个添加行按钮,但我想在行类“ title”和“ ongkir”之间添加行,但这是我的原始代码,但是在“ ongkir”之后请添加新行,请帮助我

这是我的桌子

           <table class="table table-hover order-list">
            <tr class="title">
              <th>No</th>
              <th></th>
            </tr>
            <tr>
              <td>1</td>
              <td><input type="button" style="width: 50px;" class="btn btn-success" id="addrow" value="+"></input></td>
            </tr>
            <tr class="ongkir">
              <td>JNE</td>
            </tr>
          </table>

这是我的JavaScript

$(document).ready(function () {
var counter = 2;

$("#addrow").on("click", function () {
    var newRow = $("<tr>");
    var cols = "";
    cols += '<td>'+ counter + '</td>';
    newRow.append(cols);
    $("table.order-list").append(newRow);
    counter++;
});
$("table.order-list").on("click", ".ibtnDel", function (event) {
    $(this).closest("tr").remove();       
    counter -= 1
});

});

1 个答案:

答案 0 :(得分:0)

您可以使用insertBefore函数代替append,如下所示:

$(document).ready(function () {
var counter = 2;

$("#addrow").on("click", function () {
    var newRow = $("<tr>");
    var cols = "";
    cols += '<td>'+ counter + '</td>';
    newRow.append(cols);
    newRow.insertBefore( "tr.ongkir" );
    counter++;
});
$("table.order-list").on("click", ".ibtnDel", function (event) {
    $(this).closest("tr").remove();       
    counter -= 1
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="table table-hover order-list">
            <tr class="title">
              <th>No</th>
              <th></th>
            </tr>
            <tr>
              <td>1</td>
              <td><input type="button" style="width: 50px;" class="btn btn-success" id="addrow" value="+"></input></td>
            </tr>
            <tr class="ongkir">
              <td></td>
            </tr>
          </table>

相关问题