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

AJAX读取动态表格指定行单元格值为空问题求助

解决AJAX无法获取表格单元格值的问题

看起来你遇到的问题主要有两个核心原因:循环绑定事件的变量作用域陷阱,以及单元格索引选择错误。咱们一步步来修复:

1. 先纠正单元格的选择索引

先梳理你生成的表格单元格顺序,每一行的td依次是:

  1. 日期(date)
  2. 赛事(competition)
  3. 主队名称(team1name)
  4. 主队得分(score1,可编辑)
  5. 客队得分(score2,可编辑)
  6. 客队名称(team2name)
  7. 比赛状态(matchState)
  8. 比赛ID(matchId)
  9. 操作按钮

你要获取的是主队得分、客队得分、比赛ID,对应的应该是第4、5、8个td,而不是你代码里的3、4、7。所以选择器要改成:

  • 主队得分:td:nth-of-type(4)
  • 客队得分:td:nth-of-type(5)
  • 比赛ID:td:nth-of-type(8)

另外,你的比赛ID的td用了<td type='hidden'>,这是无效写法(td没有type属性),建议改成<td style="display: none;">或者Bootstrap的d-none类,不过这不是导致值为空的直接原因,但规范写法更稳妥。

2. 修复循环绑定事件的变量作用域问题

在循环里绑定click事件时,变量i是共享的,当循环结束后,所有按钮的点击事件里的i都会变成循环的最后一个值,导致$('#matchh' + i)找不到对应的行,自然获取不到值。这里有几种解决方法:

方法一:用let声明变量(ES6+推荐)

把循环里的var i改成let i,这样每次循环的i都是独立的,不会被后续循环覆盖:

for (let i = 0; i < array.length; i++) {
    var json = array[i];
    // 你的表格行生成代码...
    
    $('#submitClose'+i).click(function(){
        const $row = $('#matchh' + i);
        $.ajax({
            url: 'closeMatch/confirm',
            data: { 
                status: "CLOSE", 
                firstScore: $row.find('td:nth-of-type(4)').text().trim(),
                secondScore: $row.find('td:nth-of-type(5)').text().trim(),
                matchId: $row.find('td:nth-of-type(8)').text().trim()
            },
            dataType: 'json',
            success: function (responseText){
                $("#closeMatches").modal('hide');
                alert(responseText);
            },
            error: function(){
                alert("FATALITYYYY!");
            }
        })
    });
}

这里加了.trim()是为了避免获取到单元格里的空白字符。

方法二:用闭包包裹点击事件(兼容ES5环境)

如果你的项目不支持ES6,就用闭包保存每次循环的i值:

for (var i = 0; i < array.length; i++) {
    var json = array[i];
    // 你的表格行生成代码...
    
    (function(index) {
        $('#submitClose'+index).click(function(){
            const $row = $('#matchh' + index);
            $.ajax({
                url: 'closeMatch/confirm',
                data: { 
                    status: "CLOSE", 
                    firstScore: $row.find('td:nth-of-type(4)').text().trim(),
                    secondScore: $row.find('td:nth-of-type(5)').text().trim(),
                    matchId: $row.find('td:nth-of-type(8)').text().trim()
                },
                dataType: 'json',
                success: function (responseText){
                    $("#closeMatches").modal('hide');
                    alert(responseText);
                },
                error: function(){
                    alert("FATALITYYYY!");
                }
            })
        });
    })(i);
}

方法三:用数据属性(更优雅的写法)

在生成按钮的时候,把需要的matchId和初始得分存在按钮的data属性里,点击时直接从按钮获取(如果允许用户编辑得分,还是需要从td里实时读取,这种方法适合初始值固定的场景):

for (var i = 0; i < array.length; i++) {
    var json = array[i];
    // 你的表格行生成代码...
    
    // 生成按钮时添加data属性
    $('#matchh' + i).append('<td><button class="btn btn-primary" id="submitClose' + i + '" data-matchid="' + json.matchId + '" data-score1="' + json.score1 + '" data-score2="' + json.score2 + '">Revert/Close</button></td>');
    $('#matchh' + i).append('</tr>');
    
    $('#submitClose'+i).click(function(){
        const $btn = $(this);
        $.ajax({
            url: 'closeMatch/confirm',
            data: { 
                status: "CLOSE", 
                firstScore: $btn.data('score1').trim(),
                secondScore: $btn.data('score2').trim(),
                matchId: $btn.data('matchid').trim()
            },
            dataType: 'json',
            success: function (responseText){
                $("#closeMatches").modal('hide');
                alert(responseText);
            },
            error: function(){
                alert("FATALITYYYY!");
            }
        })
    });
}

3. 额外调试技巧

如果修改后还是有问题,可以在点击事件里添加控制台打印,排查具体值:

const $row = $('#matchh' + i);
console.log('主队得分:', $row.find('td:nth-of-type(4)').text());
console.log('客队得分:', $row.find('td:nth-of-type(5)').text());
console.log('比赛ID:', $row.find('td:nth-of-type(8)').text());

打开浏览器控制台(F12)查看输出,就能快速定位是选择器错误还是变量作用域的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 06:58:16