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

DataTable分页后编辑按钮失效问题求助

问题解决:DataTable分页后编辑按钮仅第一页生效

问题场景

服务器渲染的表格启用DataTable分页功能后,仅第一页的「编辑」按钮能正常触发事件,第二页及后续页面的编辑按钮点击无响应。

原因分析

DataTable的分页机制会动态加载/渲染非当前页的DOM元素,初始页面加载时只有第一页的按钮存在于DOM中。原代码中$(".uniformsss").click()的写法,只会给初始DOM里的元素绑定事件,后续分页生成的新按钮不会被绑定事件,导致点击无效。

解决方法

使用事件委托(Event Delegation),将事件绑定到一个始终存在的父元素(比如表格本身或document),由父元素监听子元素的点击事件,无论元素是初始存在还是动态生成,都能触发事件。

修改后的编辑按钮事件处理代码如下:

$(document).ready(function () {
    // 事件委托绑定:父元素选表格#uni_table或document均可,推荐选更近的静态父元素
    $('#uni_table').on('click', '.uniformsss', function (e) {
        e.preventDefault();
        // 获取记录ID
        var iid = $(this).attr('data-id');
        $('#btnSubmit').trigger("reset");
        $('#exampleModal').modal('show');
        
        $.ajax({
            url: 'UniformsByID?id=' + iid,
            method: 'GET',
            data: '',
            dataType: 'json',
        }).done(function (response) {
            console.log(response);
            // 填充表单数据
            $('#btnSubmit').find('[name="id"]').val(response.uniformss.id).end();
            $('#btnSubmit').find('[name="emid"]').val(response.uniformss.em_id).end();
            $('#btnSubmit').find('[name="slips"]').val(response.uniformss.nos).end();
            $('#btnSubmit').find('[name="date"]').val(response.uniformss.date).end();
            $('#btnSubmit').find('[name="details"]').val(response.uniformss.description).end();

            $('#btnSubmit').find('[name="shirts"]').val(response.uniformss.shirt).end();
            $('#btnSubmit').find('[name="shirt_color"]').val(response.uniformss.s_color).end();
            $('#btnSubmit').find('[name="pants"]').val(response.uniformss.pants).end();
            $('#btnSubmit').find('[name="pants_color"]').val(response.uniformss.p_color).end();

            $('#btnSubmit').find('[name="tie"]').val(response.uniformss.tie).end();
            $('#btnSubmit').find('[name="cap"]').val(response.uniformss.cap).end();
            $('#btnSubmit').find('[name="ins_stripe"]').val(response.uniformss.ins_stripe).end();
            $('#btnSubmit').find('[name="crest"]').val(response.uniformss.crest).end();

            $('#btnSubmit').find('[name="star_nickle"]').val(response.uniformss.st_nickle).end();
            $('#btnSubmit').find('[name="so_pin"]').val(response.uniformss.so_pin).end();
            $('#btnSubmit').find('[name="epaulettes"]').val(response.uniformss.epaulettes).end();
            $('#btnSubmit').find('[name="shoes"]').val(response.uniformss.shoes).end();

            $('#btnSubmit').find('[name="jacket"]').val(response.uniformss.jacket).end();
        });
    });
});

补充说明

  • 事件委托的父元素优先选择离目标元素最近的静态父元素(比如这里的#uni_table),相比绑定到document性能更优。
  • 原代码中e.preventDefault(e)可简化为e.preventDefault(),无需重复传参。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 09:54:53