来自 for 计数器的 i 变量在获取每个Twitch流式传输器的每个API时都有效,但是当我使用它来生成div时,它只是8。有一种方法可以让我在获取API数据和迭代飘带时使计数器工作吗?
$(document).ready(function(){
// streamers I want to look up
var streamers = ["ESL_SC2", "OgamingSC2", "cretetion", "freecodecamp", "storbeck", "habathcx", "RobotCaleb", "noobs2ninjas"]
// counts the number of streamers in the array
for (var i = 0; i < streamers.length; i++){
// gets each streamer, one by one
$.getJSON("https://wind-bow.gomix.me/twitch-api/streams/" + streamers[i] +"?callback=?", function(json) {
//if they are not offline, pulls information from them and adds it to a div
if ((json.stream) !== null) {
$("#results").prepend("<div class = \"resultsONLINE\">" + json.stream.channel.display_name + "</div>");
// if they are offline, marks them as offline
} else {
$("#results").append("<div class = \"resultsOFFLINE\">" + streamers[i] + " is offline</div>");
}
});
};
答案 0 :(得分:0)
试试这个
$(document).ready(function(){
// streamers I want to look up
var streamers = ["ESL_SC2", "OgamingSC2", "cretetion", "freecodecamp", "storbeck", "habathcx", "RobotCaleb", "noobs2ninjas"]
// counts the number of streamers in the array
var index = 0;
for (var i = 0; i < streamers.length; i++){
// gets each streamer, one by one
$.getJSON("https://wind-bow.gomix.me/twitch-api/streams/" + streamers[i] +"?callback=?", function(json) {
//if they are not offline, pulls information from them and adds it to a div
if ((json.stream) !== null) {
$("#results").prepend("<div class = \"resultsONLINE\">" + json.stream.channel.display_name + "</div>");
// if they are offline, marks them as offline
} else {
$("#results").append("<div class = \"resultsOFFLINE\">" + streamers[index] + " is offline</div>");
}
index++;
});
};
答案 1 :(得分:0)
如果我没弄错,getJSON是一个基于承诺的函数,所以尝试使用.then(json =&gt; function()...)。
此代码应该可以正常运行。
$(document).ready(function() {
// streamers I want to look up
var streamers = [
"ESL_SC2",
"OgamingSC2",
"cretetion",
"freecodecamp",
"storbeck",
"habathcx",
"RobotCaleb",
"noobs2ninjas"
];
// counts the number of streamers in the array
var streamerLength = streamers.length;
for (var i = 0; i < streamerLength; i++) {
// gets each streamer, one by one
$.getJSON(
"https://wind-bow.glitch.me/twitch-api/streams/" + streamers[i]
).then(json => appendStreamerInfo(json));
}
function appendStreamerInfo(json) {
//if they are not offline, pulls information from them and adds it to a div
if (json.stream !== null) {
$("#results").prepend(
'<div class = "resultsONLINE">' +
json.stream.channel.display_name +
"</div>"
);
// if they are offline, marks them as offline
} else {
$("#results").append(
'<div class = "resultsOFFLINE">' + streamers[i] + " is offline</div>"
);
}
}
});