data 变量为500。此变量具有500个Hackers News热门新闻的ID。
我正在尝试添加tr元素,以显示每个ID和等级的标题。
如果我在循环中仅添加一个ID,就没有问题。
但是,如果我使用多个ID,则新的tr元素将替换旧的tr元素。
我想显示500个最佳出站,但您只看到一个故事。
有什么办法展示500个故事?
var itemlist = document.querySelector('.itemlist'); //tbody elements
var request = new XMLHttpRequest()
request.open('GET', 'https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty', true)
request.onload = function() {
// begin accessing JSON data here
var data = JSON.parse(this.response);
for (var j = 0; j < data.length; j++) {
var temp = data[j];
var id = 'https://hacker-news.firebaseio.com/v0/item/' + temp + '.json?print=pretty';
request.open('GET', id, true)
request.onload = function() {
var data = JSON.parse(this.response);
var tr = document.createElement('tr');
var td = document.createElement('td');
var td1 = document.createElement('td');
td.id = temp;
td.textContent = (j) + '.';
td1.textContent = data.title;
tr.appendChild(td);
tr.appendChild(td1);
itemlist.appendChild(tr);
console.log(id);
}
request.send();
}
}
request.send();
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<link rel="stylesheet" href="CSS/style.css">
</head>
<body>
<table class="main" width="85%">
<tbody>
<tr>
<td bgcolor="#ff6600">
<table style="padding:2px;">
<tbody>
<tr>
<td style="width:18px;">
<a href="https://news.ycombinator.com/">
<img src="https://news.ycombinator.com/y18.gif" class="ylogo">
</a>
</td>
<td style="line-height:12px;height:10px">
<span class="mainmenu">
<span style="margin-right:7px;">
<a href="">Hacker News</a>
</span>
<a href="">new</a>
<a href="">|</a>
<a href="">past</a>
<a href="">|</a>
<a href="">comments</a>
<a href="">|</a>
<a href="">ask</a>
<a href="">|</a>
<a href="">show</a>
<a href="">|</a>
<a href="">jobs</a>
<a href="">|</a>
<a href="">submit</a>
</span>
</td>
</tr>
</tbody>
</table>
</td>
</tr>
<tr class="pagespace"></tr>
<tr>
<td>
<table>
<tbody class="itemlist">
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
<script src="main.js"></script>
</body>
</html>