javascript - 添加具有特定行类的行
问题描述
我有 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
});
});
解决方案
您可以使用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>
推荐阅读
- mysql - MySQL:计算过去 12 个月的数据
- snowflake-cloud-data-platform - 无符号 MD5_Number_Lower64 哈希结果
- kubernetes - 更改 k8s API 的组名和版本
- java - 这个二叉树代码在java中是如何工作的?
- hive - 映射器倾斜和输入拆分大小
- r - 有效地找到 R 中两个时间间隔之间的重叠
- c++ - 为什么我不能在 c++ 中的 neovim shell 模拟器中输入?
- r - 错误:使用 tidymodels 工作流预测测试集时出现“列中缺少数据”
- spring-boot - Github Action:如何在构建步骤之前向 application.properties 文件添加机密
- javascript - LocalStorage 到 fastAPI(txt 或 sqlite)以保存数据(应用程序:便笺)