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

DataTables表格编辑删除按钮仅首页生效(Ajax+jQuery开发)问题求助

问题根因

你当前的点击事件是直接绑定在.edit_product、.delete_product类对应的DOM元素上的,仅页面初始化时已渲染的元素(也就是表格第一页的按钮)能成功绑定事件。DataTables切换分页时会动态销毁旧行、渲染新行,后续分页生成的按钮没有被绑定点击事件,因此点击无响应。

解决方案

将直接绑定的点击事件改为事件委托模式,把事件绑定到页面初始化时就存在、不会被动态销毁的父级元素上(比如document、表格外层容器等),即可适配所有动态生成的按钮元素。

修改后的编辑功能代码

// 把原来的$('.edit_product').click(function(){ 替换为下面的写法,内部逻辑完全不变
$(document).on('click', '.edit_product', function(){
    start_load()
    var cat = $('#manage-product')
    cat.get(0).reset()
    cat.find("[name='id']").val($(this).attr('data-id'))
    cat.find("[name='name']").val($(this).attr('data-name'))
    cat.find("[name='sku']").val($(this).attr('data-sku'))
    cat.find("[name='category_id']").val($(this).attr('data-category_id'))
    cat.find("[name='description']").val($(this).attr('data-description'))
    cat.find("[name='price']").val($(this).attr('data-price'))
    cat.find("[name='cprice']").val($(this).attr('data-cprice'))
    cat.find("[name='pdate']").val($(this).attr('data-pdate'))
    cat.find("[name='expdate']").val($(this).attr('data-expdate'))
    end_load()
})

修改后的删除功能代码

// 把原来的$('.delete_product').click(function(){ 替换为下面的写法,内部逻辑完全不变
$(document).on('click', '.delete_product', function(){
    _conf("Are you sure to delete this product?","delete_product",[$(this).attr('data-id')])
})
function delete_product($id){
    start_load()
    $.ajax({
        url:'ajax.php?action=delete_product',
        method:'POST',
        data:{id:$id},
        success:function(resp){
            if(resp==1){
                alert_toast("Data successfully deleted",'success')
                setTimeout(function(){
                    location.reload()
                },1500)
            }
        }
    })
}

可选优化

你可以用jQuery的data()方法读取自定义属性,写法更简洁,比如把$(this).attr('data-id')替换为$(this).data('id'),功能完全一致。


内容的提问来源于stack exchange,提问作者Mike Chinwendu Nwogu

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 12:06:03