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

JSON转HTML表格报错:Cannot set properties of null 求助

解决表格渲染时的"Cannot set properties of null"错误及表格结构问题

错误原因及修复方案:

  1. getElementById参数错误
    原代码中使用document.getElementById("#stats-output")是错误的,getElementById的参数仅需传入元素的id值,不需要加CSS选择器的#符号。这是导致output变量为null,进而触发设置innerHTML时报错的直接原因。

    修复代码:

    let output = document.getElementById("stats-output");
    
  2. 表格行结构缺失
    原代码生成的HTML仅包含<td>标签,未用<tr>包裹每一行数据,不符合表格的HTML结构规范,即使解决了元素获取问题,表格也无法正常渲染。需要为每个球员的数据包裹<tr>标签:

    val.forEach((player, index) =>{
        console.log(player);
        html += `
            <tr>
                <td>${player.Position}</td>
                <td>${player.Name}</td>
                <td>${player.Apperiences}</td>
                <td>${player.Goals || 0}</td>
                <td>${player.Assists}</td>
                <td>${player.Clean_Sheets}</td>
            </tr>
        `;
    })
    
  3. 缺失字段补充处理
    HTML表头包含"Goals"列,但JSON数据中无对应字段,可通过player.Goals || 0设置默认值,避免表格出现空白单元格。

完整修复后的JS代码:

fetch("data.json")
.then(response => response.json())
.then(data => {
    outData(data.Sheet1);
})

function outData(val){
    console.log(val);
    let output = document.getElementById("stats-output");
    let html = '';
    val.forEach((player, index) =>{
        console.log(player);
        html += `
            <tr>
                <td>${player.Position}</td>
                <td>${player.Name}</td>
                <td>${player.Apperiences}</td>
                <td>${player.Goals || 0}</td>
                <td>${player.Assists}</td>
                <td>${player.Clean_Sheets}</td>
            </tr>
        `;
    })
    output.innerHTML = html;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 18:27:30