首页 > 解决方案 > Javascript - 获取练习(Github 用户)

问题描述

我正在尝试使用 Github 用户的用户名给出的 JSON 调用创建一个表。Github 回购

我能够做到这一点(它显示用户名,头像和生物),但我正在努力在多行上做到这一点。我自己尝试了一段时间。我认为我非常接近解决方案,但我仍然无法用元素填充每一行。任何人都可以帮助输入(请检查 Javascript)?非常感谢。

代码:

//Step1
var users = [];

for (var i = 0; i < 2; i++) {

  users.push(prompt('Enter your Github user name'));

}

for (var user of users) {
  fetch(`https://api.github.com/users/${user}`).then((response) => {

    return response.json();

  }).then((responseJson) => {

    console.log(responseJson);
    injectInfo(responseJson);

  });
}

//Step2
function injectInfo(responseJson) {

  //How I am trying to populate the other lines
  var table = document.getElementById('myTable');
  var row = table.insertRow(2);

  for (var c = 0; c < 3; c++) {

    var cell = row.insertCell(c);

  };

  //How to populate one line
  document.querySelector('.username__cell').innerHTML = responseJson.login;
  document.querySelector('.avatar__cell').innerHTML = responseJson.avatar_url;
  document.querySelector('.bio__cell').innerHTML = responseJson.bio;

  var avatar = document.createElement('img');
  var src = document.querySelector('.avatar__cell');
  avatar.src = responseJson.avatar_url;
  src.appendChild(avatar);

}
<!doctype html>
<html lang="en">
  <head>
      <title>Fetch</title>
  </head>
  <body>

    <table style="width:100%; border: solid 1px black;" id="myTable">
      <tr>
        <th>Username</th>
        <th>Avatar</th>
        <th>Bio</th>
      </tr>
      <tr>
        <td class="username__cell"></td>
        <td class="avatar__cell"></td>
        <td class="bio__cell"></td>
      </tr>
    </table>

    <script src="fetch.js"></script>
</body>
</html>

标签: javascriptarraysfor-loopfetch

解决方案


您不会将数据填充到您插入的行中,而是每次都修改同一行并覆盖内容。

//Step1
let users = [];

for (let i = 0; i < 2; i++) {
    users.push(prompt('Enter your Github user name'));
}

for (let user of users) {
    fetch(`https://api.github.com/users/${user}`).then(response => {
        return response.json();
    }).then(responseJson => {
        injectInfo(responseJson);
    });
}

//Step2
function injectInfo(responseJson) {
    let table = document.getElementById('myTable'),
        row = table.insertRow(1),
        cell0 = row.insertCell(0),
        cell1 = row.insertCell(1),
        cell2 = row.insertCell(2),
        cell3 = row.insertCell(3);
      
    cell0.innerHTML = responseJson.login;
    cell1.innerHTML = responseJson.avatar_url;
    cell2.innerHTML = responseJson.bio;
  
    let avatar = document.createElement('img');
    avatar.src = responseJson.avatar_url;
    cell3.appendChild(avatar);
}
#myTable tr > td > img {
    width: 50px;
    height: auto;
}
<table style="width:100%; border: solid 1px black;" id="myTable">
    <tr>
        <th>Username</th>
        <th>Avatar</th>
        <th>Bio</th>
    </tr>
</table>


推荐阅读