我怎么能通过

时间:2018-05-22 17:35:28

标签: javascript jquery for-loop getjson

var url1="https://wind-bow.glitch.me/twitch-api/streams/";
var channelList= ["channel1","channel2",channel3"];



//I am trying to create for loop to define url with different channel names.

for(var i=0;i<channelList.length;i++){
  var url="https://wind-bow.glitch.me/twitch-api/channels/" + channelList[i];
  $.getJSON(url1+channelList[i],function(data){

    //When the user click off button,I want to show offline channels.
    $("#off").on("click", () => {
      if(data.stream === null) {
        $.getJSON(url,function(seconddata){

          $("#main").append("<div class='row' style='margin-top:5px;'><div class='col-md-4'><p><img src='"+seconddata.logo+"'width='42' height='42'>"+"      "+"<a href='"+seconddata.url+"' target=_blank>"+seconddata.display_name+"</a></p></div></div>")   
      });
    }
  });      
});

你好,我真的很喜欢编码。现在我跟随FreeCodeCamp,我正在努力与Twitch查看器项目。但我被困在代码上:)  我想创建一个for循环并使用api来获取所有通道的数据。但是我只得到最后一个通道的数据,因为“i”在jquery函数之外增加了。它不是通过jquery函数。我该如何解决? :)

提前感谢您的回复。

注意:抱歉我的英文。这不是我的母语。 :)我希望你能理解我的问题。

1 个答案:

答案 0 :(得分:1)

尝试类似以下代码段的逻辑。

var url1="https://wind-bow.glitch.me/twitch-api/streams/";
var channelList= ["channel1","channel2","channel3"];

var allData = [];

//I am trying to create for loop to define url with different channel names.

for(var i=0;i<channelList.length;i++) {
  var url="https://wind-bow.glitch.me/twitch-api/channels/" + channelList[i];
  $.getJSON(url1+channelList[i],function(data){
    allData.push(data);
  });
};

   //When the user click off button,I want to show offline channels.
    $("#off").on("click", () => {
      for (var j=0;j<channelList.length; j++) {
        var data = allData[j];
        if(data.stream === null) {
        $.getJSON(url,function(seconddata){

          $("#main").append("<div class='row' style='margin-top:5px;'><div class='col-md-4'><p><img src='"+seconddata.logo+"'width='42' height='42'>"+"      "+"<a href='"+seconddata.url+"' target=_blank>"+seconddata.display_name+"</a></p></div></div>") 


        });
       }
    }
  });