使用JavaScript Fetch实现GitHub用户信息多行表格的问题求助
解决GitHub用户信息表格多行填充问题
我看了你的代码,问题核心在于你每次获取到新用户数据后,虽然插入了新行,但始终在修改页面初始的那一行单元格,而非新创建的行。这就导致新数据不断覆盖第一行,新插入的行却一直是空的。下面具体说问题点和修复方案:
问题分析
- 选择器错误:
document.querySelector('.username__cell')这类选择器只会选中页面中第一个匹配类名的元素,也就是表格里一开始就存在的那行单元格。每次获取新用户数据时,你都在覆盖这同一个单元格的内容,而非新行的单元格。 - 固定行位置:
table.insertRow(2)会把新行固定插入到索引为2的位置(表头是索引0,初始数据行是索引1),当输入第3个及以上用户时,行插入位置会出错,应该把新行添加到表格末尾。
修复后的代码
JavaScript部分(fetch.js)
// Step1 var users = []; for (var i = 0; i < 2; i++) { users.push(prompt('Enter your Github user name')); } // 遍历用户列表获取数据 users.forEach(user => { fetch(`https://api.github.com/users/${user}`) .then(response => response.json()) .then(responseJson => { console.log(responseJson); injectInfo(responseJson); }) .catch(err => console.error('获取用户数据失败:', err)); // 新增错误处理,方便排查问题 }); // Step2 function injectInfo(responseJson) { var table = document.getElementById('myTable'); // 插入新行到表格末尾(不传参数默认就是最后一行) var row = table.insertRow(); // 创建Username单元格并填充内容 var usernameCell = row.insertCell(0); usernameCell.textContent = responseJson.login; usernameCell.classList.add('username__cell'); // 可选:保留类名方便后续样式调整 // 创建Avatar单元格并添加头像图片 var avatarCell = row.insertCell(1); var avatarImg = document.createElement('img'); avatarImg.src = responseJson.avatar_url; avatarImg.alt = `${responseJson.login}'s avatar`; // 新增alt属性,提升可访问性 avatarImg.style.width = '50px'; // 可选:设置头像大小 avatarCell.appendChild(avatarImg); avatarCell.classList.add('avatar__cell'); // 创建Bio单元格并填充内容,处理bio为空的情况 var bioCell = row.insertCell(2); bioCell.textContent = responseJson.bio || 'No bio provided'; bioCell.classList.add('bio__cell'); }
HTML部分
<!doctype html> <html lang="en"> <head> <title>Fetch GitHub Users</title> <style> /* 可选:添加表格样式提升视觉效果 */ table { width: 100%; border-collapse: collapse; margin-top: 20px; } th, td { border: solid 1px black; padding: 8px; text-align: left; } th { background-color: #f2f2f2; } </style> </head> <body> <table id="myTable"> <tr> <th>Username</th> <th>Avatar</th> <th>Bio</th> </tr> <!-- 移除初始数据行,所有数据行通过JS动态生成 --> </table> <script src="fetch.js"></script> </body> </html>
改动说明
- 动态操作新行单元格:不再使用
querySelector去选择已有元素,而是直接操作新创建的row和cell对象,确保每个用户数据都填充到对应的新行里。 - 插入行到末尾:
table.insertRow()默认将新行添加到表格最后,不管有多少用户,行位置都不会出错。 - 错误处理:给
fetch添加了catch块,方便排查获取数据失败的问题。 - 细节优化:处理了bio为空的情况,给图片添加alt属性,可选添加样式让表格更美观。
内容的提问来源于stack exchange,提问作者user10905498
相关产品推荐
相关产品推荐

