javascript - 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>
解决方案
您不会将数据填充到您插入的行中,而是每次都修改同一行并覆盖内容。
//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>
推荐阅读
- php - 在 PHP 中用 OR 比较两个字符串
- matlab - 如何在我的数据集上应用不归一化的 k-means 和带归一化的 k-means?
- python - Python 3,“RecursionError:编译期间超出最大递归深度”
- ios - UITextfiled 的 leftView 属性在 Objective-C 中不起作用
- c# - 屏幕截图未使用范围报告版本 4 - Selenium C# 捕获
- apache-spark - 无法加载 com.saprk.demo.Hive。java.lang.ClassNotFoundException:com.saprk.demo.Hive
- shake-build-system - 如何使用抖动跟踪“运行时”依赖项?
- mysql - Sql 查询以使用 Laravel 检索所有记录以及按外键排序的关系
- c# - 在 Swagger 中禁用“试用”
- javascript - 如何取消选中角度6中的所有选中复选框