好的。因此,下面的代码只从列表中获取第一个通道,我希望它从JSON中获取所有流。(额外的问题:我如何将所有获取的流格式化为一个很好的逐行网格,其中每个行都有三个流)
<script>
var twitchApi = "https://api.twitch.tv/kraken/streams";
$.getJSON(twitchApi, function (json) {
var streamGame = json.streams[0].game;
var streamThumb = json.streams[0].preview;
var streamVideo = json.streams[0].name;
$('#twitch').append('<li><iframe src="http://player.twitch.tv/?channel=' + streamVideo + '"></iframe></li>');
}
);
</script>
我需要帮助的第二件事是如何创建一个脚本,从这个JSON中获取前10个游戏:https://api.twitch.tv/kraken/games/top。应该和上面的非常相似,但是我的大脑已经冻结了,我需要完成这个任务。
发布于 2016-05-16 21:16:45
为了使用相同的数据同时获取多个流,可以使用 For 循环。
修正了streamVideo变量,".channel“在”.name“之前丢失了(我建议使用JSON查看器来获得结构的清晰远景,比如在线JSON查看器 )
并使脚本显示10个iframes (还从twitch抓取嵌入代码,您的嵌入非常小)。
我让它成为你自己的风格,我对造型一窍不通,你可以试着为每一行设置30%的宽度,这样每一行就有3个,而其他的则在最下面的行。
var twitchApi = "https://api.twitch.tv/kraken/streams";
$.getJSON(twitchApi, function(json) {
for (i = 0; i < 10; i++) {
var streamGame = json.streams[i].game;
var streamThumb = json.streams[i].preview;
var streamVideo = json.streams[i].channel.name;
$('#twitch').append('<li><iframe src="https://player.twitch.tv/?channel=' + streamVideo + '" frameborder="0" scrolling="no" height="378" width="620"></iframe><li>');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
发布于 2016-05-16 21:34:24
您可以通过循环和内联块元素的组合来完成所需的任务。在这里,我使用jQuery创建三个单元格的行。
var twitchApi = "https://api.twitch.tv/kraken/streams";
$.getJSON(twitchApi, function (json) {
var streamRow = $("<div class='stream-row'></div>").appendTo("#twitch"); // Create first row.
var streamCell;
var streamVideo;
for (var i = 0; i < json.streams.length; i++)
{
if (i % 3 == 0 && i > 0)
{
// Create a new row every multiple of 3.
streamRow = $("<div class='stream-row'></div>");
$("#twitch").append(streamRow);
}
// Create a cell with a video and add it to the row.
streamVideo = json.streams[i].channel.name;
streamCell = $("<div>", {
css: {
"class": "stream-cell",
"display": "inline-block"
}
});
streamCell.append('<iframe src="http://player.twitch.tv/?channel=' + streamVideo + '"></iframe>');
streamRow.append(streamCell);
}
});
你用另一个循环来做前十件事。API已经返回了10个游戏,所以我使用长度而不是硬编码10。
var twitchApi = "https://api.twitch.tv/kraken/games/top";
$.getJSON(twitchApi, function (json) {
for (var i = 0; i < json.top.length; i++)
{
// Do whatever you need here with the info from the JSON.
console.log(json.top[i].game.name)
}
});
https://stackoverflow.com/questions/37262809
复制相似问题