You need to enable JavaScript to run this app. Ajax修改表格数据仅首行生效其余行无响应如何解决
优惠活动
大模型
产品
解决方案
定价
更多

Ajax修改表格数据仅首行生效其余行无响应如何解决

问题根因

  • 你使用了全局ID选择器$("#test1")、$("#test2")获取值,HTML规范中ID是全局唯一的,因此不管触发哪一行的change事件,永远只会匹配到第一行对应ID的元素,无法获取当前行的input值
  • 代码中定义的参数对象名称为test,但AJAX请求的data字段传入的是未定义的alta变量,属于语法错误

修正后的代码

$(document).ready(function(){
    $('#table').on('change', 'input', function () {
        // 获取当前触发事件的input所属的行
        const $currentRow = $(this).closest('tr');
        // 基于当前行范围查找对应input,不要用全局ID选择器
        var test={
            "test1": $currentRow.find(".test1").val(),
            "test2": $currentRow.find(".test2").val()
        }
        $.ajax({
            method: "POST",
            url:    "data.php",
            data: test, // 修正变量名错误
            async:true,
            cache:false,
            success : function(response){
                if(response=="1"){
                    alert("done");
                } 
                else{
                    alert("sad");
                }
            },
            error : function(error) {
                alert(error);
            }
        });
    });
});

配套HTML调整要求

修改表格模板代码,把原来每行重复的id="test1"、id="test2"属性改为class="test1"、class="test2",避免ID重复冲突。如果不想用类选择器,也可以用name属性匹配:$currentRow.find('[name="test1"]').val()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.16 14:24:08