首页 > 解决方案 > 对多个 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>

标签: javascripthtml

解决方案


你是这个意思?

不要从 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();
  });
});

推荐阅读