繁体   English   中英

对多个 HTML 表使用相同的 JS function?

[英]Using same JS function for multiple HTML tables?

我有 function 在单击按钮时添加和删除表的行,即add_row 现在我有多个表,我想在同一页面上使用相同的 function。

所以下面的 function 是表 1,我如何为表 2、表 3 重用相同的 function 等? 每个表都有自己的 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();
  });
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM