代码之家  ›  专栏  ›  技术社区  ›  ThoughtfulCollector

jQuery appendTo忽略最后一个元素

  •  1
  • ThoughtfulCollector  · 技术社区  · 2 年前

    Live example on JSFiddle

    var count = 1;
    
    $("#addBtn").click(function(){
      $('#trid1').clone().appendTo('table#exampleTable > tbody');
      count++;
      $('#trid1').last().prop('id', 'trid'+count);
      $('#trid'+count+' > th').html(count);
    });
    <!-- jQuery -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    
    <table class="table" id="exampleTable">
      <thead>
        <tr>
          <th scope="col">c1</th>
        </tr>
      </thead>
      <tbody>
        <tr id="trid1" class="trclass">
          <th scope="row">1</th>
        </tr>
      </tbody>
    </table>
    <button type="button" id="addBtn">Add</button>
    1 回复  |  直到 2 年前
        1
  •  0
  •   Diego D    2 年前

    无论如何,我考虑到了这个策略,稍微重构了您的代码,并且在每次单击add按钮时更好地处理当前索引。最新索引保存在表中的数据属性中。

    $("#addBtn").click(function(){
      const latestIndex = $('#exampleTable').data('latest-index');
      let i = latestIndex+1;
      const newRow = $('#trid1').clone();
      newRow.prop('id', `trid${i}`);
      newRow.data('index', i);
      newRow.text(i);
      newRow.appendTo('table#exampleTable > tbody');
      $('#exampleTable').data('latest-index', i);
    });
    button{
      cursor: pointer;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <table class="table" id="exampleTable" data-latest-index="1">
      <thead>
        <tr>
          <th scope="col">Rows</th>
        </tr>
      </thead>
      <tbody>
        <tr id="trid1" class="trclass">
          <th scope="row">1</th>
        </tr>
      </tbody>
    </table>
    <button type="button" id="addBtn">Add</button>