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

HTML表格拖拽行时如何实现行号自动调整?

解决方案

你可以直接利用jQuery UI Sortable 自带的stop拖拽结束回调事件,在每次行调整完成后遍历所有行更新第一列的行号即可。

首先你需要修改sortable的初始化代码,补充回调逻辑:

$('tbody').sortable({
    // 拖拽动作结束后触发
    stop: function () {
        // 遍历tbody下所有行,index从0开始计数
        $('tbody tr').each(function (index) {
            // 给当前行第一列td赋值为索引+1(行号从1开始)
            $(this).find('td:first').text(index + 1);
        });
    }
});

var checklistContentTableOnSort = document.getElementById('table');

可选优化(非必需)

如果你的业务逻辑需要同步更新每行input的name属性、行id属性和排序后的序号匹配,可以在回调里补充对应逻辑,示例如下:

stop: function () {
    $('tbody tr').each(function (index) {
        $(this).find('td:first').text(index + 1);
        // 同步更新行id
        $(this).attr('id', 'addr' + index);
        // 同步更新两个input的name属性
        $(this).find('input[name^="text"]').attr('name', 'text' + index);
        $(this).find('input[name^="comment"]').attr('name', 'comment' + index);
    });
}

注意事项

如果你的页面目前还没引入jQuery UI依赖,需要在jQuery引入后补充引入jQuery UI的脚本,才能正常使用sortable功能。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 03:15:07