首页 > 解决方案 > 添加具有特定行类的行

问题描述

我有 2 个列和 1 个添加行按钮,但我想在行类“标题”和“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
});

});

标签: javascriptjqueryhtml

解决方案


您可以使用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>


推荐阅读