JSON转HTML表格报错:Cannot set properties of null 求助
解决表格渲染时的"Cannot set properties of null"错误及表格结构问题
错误原因及修复方案:
getElementById参数错误
原代码中使用document.getElementById("#stats-output")是错误的,getElementById的参数仅需传入元素的id值,不需要加CSS选择器的#符号。这是导致output变量为null,进而触发设置innerHTML时报错的直接原因。修复代码:
let output = document.getElementById("stats-output");表格行结构缺失
原代码生成的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> `; })缺失字段补充处理
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
相关产品推荐
相关产品推荐

