You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用JQuery替换表格中的两行数据?

实现两行替换的解决方案

没问题,当然可以实现一次性替换两行!你当前的代码只替换了按钮所在的那一行<tr>,而原来紧跟在它后面的.table_hidden行还留在DOM里,所以才会出现“替换一行并新增一行”的情况。我们只需要调整选择器,把要替换的两行都选中,再一起替换成新的内容就可以了。

问题根源

你的代码中$(this).closest('tr')仅选中了点击按钮所在的那一行,替换时新内容里的两行会把这一行替换掉,但原来的隐藏行还保留着,导致最终DOM里多了一行。

修改后的代码

HTML(保持不变)

<div class="container"> 
  <table class="table" id="data_table">
    <tbody>
      <tr>
        <th></th> 
        <th></th>
        <th></th> 
      </tr> 
      <tr class="table">
        <td></td>
        <td class="prod">First cell</td>
        <td class="prod">Second cell</td>
        <td class="prod">Third Cell</td>
        <td> 
          <button type="button" id="btn1" class="add-row">Replace Row</button>
        </td> 
      </tr> 
      <tr class="table_hidden">
        <td></td>
        <td>1a</td>
        <td>2a</td>
        <td>3a</td>
        <td></td>
      </tr> 
      <tr class="table">
        <td></td>
        <td class="prod">Fourth Cell</td>
        <td class="prod">Fifth cell</td>
        <td class="prod">Sixth Cell</td>
        <td> 
          <button type="button" id="btn2" class="add-row">Replace Row</button>
        </td> 
      </tr> 
      <tr class="table_hidden">
        <td></td>
        <td>4a</td>
        <td>5a</td>
        <td>6a</td>
        <td></td>
      </tr> 
      <tr class="table">
        <td></td>
        <td class="prod">Seventh</td>
        <td class="prod">Eighth</td>
        <td class="prod">Ninth</td>
        <td> 
          <button type="button" id="btn3" class="add-row">Replace Row</button>
        </td>
      </tr> 
      <tr class="table_hidden">
        <td></td>
        <td>7a</td>
        <td>8a</td>
        <td>9a</td>
        <td></td>
      </tr> 
    </tbody>
  </table> 
</div>

jQuery(修改选择器部分)

$('#data_table').on("click", ".add-row", function() { 
  var newdata= '<tr class="table"><td></td><td class="prod">10</td><td class="prod">11</td><td class="prod">12</td><td><button type="button" id="btn1" class="add-row">Replace Row</button></td></tr><tr class="table_hidden"><td></td><td>a</td><td>b</td><td>c</td><td></td></tr>';
  // 选中当前按钮所在行 + 紧跟其后的.table_hidden行,一起替换
  $(this).closest('tr').next('.table_hidden').addBack().replaceWith(newdata); 
});

代码解释

  • $(this).closest('tr'):找到点击按钮所在的.table行
  • .next('.table_hidden'):获取这一行后面紧跟的隐藏行
  • .addBack():把之前选中的当前行也加入到选择集合中,这样就同时选中了要替换的两行
  • 最后用replaceWith(newdata)把这两行一起替换成新的两行内容

这样点击按钮时,就会一次性替换掉原来的显示行和隐藏行,不会出现多余的行啦。

内容的提问来源于stack exchange,提问作者JulianJ

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 07:53:10