javascript - 对多个 HTML 表使用相同的 JS 函数?
问题描述
我有在点击按钮时添加和删除表格行的功能,即add_row
。现在我有多个表,我想在同一页面上使用相同的功能。
所以下面的函数是针对table1的,我如何为table2、table3 ..等重用相同的函数?每个表都有自己的 add_row 按钮,即 add_row、add_row1、add_row2 等。
<script type="text/javascript">
$(document).ready(function() {
var rowIdx = 0;
$('#add_row').on('click', function () {
$.each($("#table1 tr"), function() {
if (parseInt($(this).data("id")) > rowIdx) {
rowIdx = parseInt($(this).data("id"));
console.log(rowIdx)
}
});
rowIdx++;
$('#table1').append(`<tr id="addr${rowIdx}" data-id="${rowIdx}" class="hidden">
<td data-name="id">
<input type="text" name='id${rowIdx}' placeholder='ID' value=""`);
});
$('#table1').on('click', '.remove', function () {
var child = $(this).closest('tr').nextAll();
child.each(function () {
var id = $(this).attr('id');
var idx = $(this).children('.row-index').children('p');
var dig = parseInt(id.substring(4));
idx.html(`Row ${dig - 1}`);
$(this).attr('id', `addr${dig - 1}`);
});
$(this).closest('tr').remove();
rowIdx--;
}
);
});
</script>
解决方案
你是这个意思?
不要从 rowIndex 中加减。每桌不一样。使用特定表中的实际行数
$(function() {
$('.add_row').on('click', function() {
const $table = $(this).closest("table");
const $rows = $table.find("tr");
let rowIndex = $rows.length;
$table.append(`<tr id="addr${rowIdx}" data-id="${rowIdx}" class="hidden">
<td data-name="id"><input type="text" name='id${rowIdx}' placeholder='ID' value=""</td></tr>`);
});
$(document).on('click', '.remove', function() {
var child = $(this).closest('tr').nextAll();
child.each(function() {
var id = $(this).attr('id');
var idx = $(this).children('.row-index').children('p');
var dig = parseInt(id.substring(4));
idx.html(`Row ${dig - 1}`);
$(this).attr('id', `addr${dig - 1}`);
});
$(this).closest('tr').remove();
});
});
推荐阅读
- javascript - 为csv数据JS动态添加列
- javascript - 使用 Permissions API revoke 重置地理位置权限
- javascript - 具有动画逻辑和进度传递的 React (Native) 高阶组件
- haskell - Haskell 映射树
- reactjs - React Js Card 组件不支持边框宽度和颜色
- ssl - 没有用于 MQ 通道的 SSL 或 TLS 证书(从终端运行 - Windows 10)
- laravel - Laravel 验证邮箱
- python - TypeError:不支持的格式字符串传递给 NoneType.__format__(我不知道这是什么意思)
- arrays - discord.js 宠物小精灵过滤器 cmd 与数组
- uproot - 将 ROOT 文件读取到数据帧:uproot 比 root_numpy 的 tree2array 慢