我真的迷失了这个项目,我基本上想要制作一个显示抽搐频道状态的页面。 这是codepen link。
问题是循环似乎在else语句完成之前完成,所以它每次只显示1个频道信息。它只是搞砸了。
我只想显示我的频道数组中每个抽搐频道的一些信息。
$(document).ready(function(){
function gatherChannels(){
var channels = ["ESL_SC2", "OgamingSC2", "cretetion", "freecodecamp", "storbeck", "habathcx", "RobotCaleb", "noobs2ninjas"];
for(var i=0;i<channels.length;i++){
currentChannel = channels[i];
(function(someVar){ //<-- and u will get it here
currentChannel = channels[someVar]; // all ur code
})(i);//< -- here u pass ur loop i value
$.getJSON("https://api.twitch.tv/kraken/streams/" + channels[i] + "?callback=?", function(data){
if (data.stream !== null){
$(".main-area").append("<div class ='channels' id='currentChannel'>" + data.stream.channel.status + "</div>");
}
else{
$.getJSON("https://api.twitch.tv/kraken/channels/" + currentChannel + "?callback=?", function(info){
$(".main-area").append("<div class ='channels' id='currentChannel'>" + info.url + "</div>");
});
}
});
}
}
gatherChannels();
});
答案 0 :(得分:0)
您的currentChannel变量正在循环中设置,循环正在修改,当您的第一个ajax请求返回时,循环已经结束,这就是为什么您的info.url是最后一个。
你可以将你的ajax调用放入它自己的函数中,如下所示。
$(document).ready(function() {
function gatherChannels() {
var channels = ["ESL_SC2", "OgamingSC2", "cretetion", "freecodecamp", "storbeck", "habathcx", "RobotCaleb", "noobs2ninjas"],
getChannel = function getChannel(channel) {
$.getJSON("https://api.twitch.tv/kraken/streams/" + channel + "?callback=?", function(data) {
if (data.stream !== null) {
$(".main-area").append("<div class ='channels' id='currentChannel" + channel + "'>" + data.stream.channel.status + "</div>");
} else {
$.getJSON("https://api.twitch.tv/kraken/channels/" + channel + "?callback=?", function(info) {
$(".main-area").append("<div class ='channels' id='currentChannel'" + channel + ">" + info.url + "</div>");
});
}
});
}
for (var i = 0; i < channels.length; i++) {
getChannel(channels[i]);
}
}
gatherChannels();
});
&#13;
body {
background-color: black;
color: #fff;
}
h1 {
text-align: center;
background-color: gray;
padding: 20px;
}
.main-area {
margin-left: auto;
margin-right: auto;
}
.channels {
background: blue;
margin-top: 10px;
margin-left: auto;
margin-right: auto;
color: white;
}
&#13;
<html>
<head>
<title>Twitch Streamer Status</title>
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
<div class="container">
<div class="main-area">
<h1>Twitch Streamers</h1>
</div>
</div>
</body>
</html>
&#13;