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

如何通过点击按钮将HTML表格中的对应行向上移动一行

表格行点击上移实现方案

现有代码问题

  • jQuery 1.9及以上版本已废弃live方法,推荐使用on方法做事件委托
  • 选择器逻辑错误:按钮没有设置oben类,不能用.oben类选择器匹配元素
  • 行移动逻辑冗余:不需要先删除再克隆行,可直接调整DOM节点位置
  • 缺少边界判断:第一行没有上一行,无需执行上移操作
  • 原表格第二行的<td>数量和表头列数不匹配,会导致表格渲染错位,建议补全对应单元格

优化后完整代码

HTML部分

<table id="Tabelle1">
  <thead>
    <th></th>
    <th>ID</th>
    <th>NAME</th>
    <th>Nachname</th>
  </thead>
  <tbody>
    <tr>
      <td><input type="button" value="oben" class="up-btn"></td>
      <td>1</td>
      <td>Davin</td>
      <td>Humburg</td>
    </tr>
    <tr>
      <td><input type="button" value="oben" class="up-btn"></td>
      <td>2</td> <!-- 补全缺失的ID列 -->
      <td>David</td>
      <td>Hamburg</td>
    </tr>
    <tr>
      <td><input type="button" value="oben" class="up-btn"></td>
      <td>3</td>
      <td>测试名</td>
      <td>测试姓</td>
    </tr>
  </tbody>
</table>

JS部分

$(document).ready(function() {
  // 事件委托绑定点击事件,兼容后续动态新增的行
  $("#Tabelle1").on("click", ".up-btn", function() {
    // 获取当前按钮所在的行
    const currentRow = $(this).closest("tr");
    // 获取当前行的上一行
    const prevRow = currentRow.prev("tr");
    // 存在上一行时才执行移动操作
    if (prevRow.length) {
      currentRow.insertBefore(prevRow);
    }
  });
});

实现逻辑

  • 给按钮添加统一类名up-btn,方便选择器匹配
  • 通过事件委托绑定点击事件,后续动态新增的行也能触发上移逻辑,不需要重新绑定事件
  • 点击按钮后先获取当前行和上一行元素
  • 判断上一行存在后,通过jQuery的insertBefore方法直接将当前行插入到上一行之前,完成上移操作

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 16:36:05