将变量传递给回调函数

时间:2018-01-29 09:40:45

标签: javascript jquery html api

我正在通过freecodecamp工作,我被困在一个项目中,我必须获得Twitch流列表的状态。 API响应不包含我正在查询的流的名称,因此我无法弄清楚如何建立从流名称到响应的连接。我已经尝试了几件事,但我可以解决这个问题。

Here's the jsfiddle of my current attempt

代码看起来像这样:

  var twitchApiEndpoint = "https://wind-bow.glitch.me/twitch-api";
  var streamsToGet = ["ESL_SC2", "OgamingSC2", "cretetion", "freecodecamp", "storbeck", "habathcx", "RobotCaleb", "noobs2ninjas"];
  var streamsStatuses = [];
  $(document).ready(getEntries);

  function getEntries() {

    for (var i = 0; i < streamsToGet.length; i++) {

      $.getJSON(twitchApiEndpoint + "/streams/" + streamsToGet[i], function(json) {
        if (json.stream == null) {
          var streamStatus = "offline";
        } else {
          var streamStatus = json.stream.game;
        }

        $(".main").append('<div class="row stream-entry" id="' + i + '"><div class="col stream-title">' + streamsToGet[i] + '</div><div class="col stream-description">' + streamStatus + '</div>');

      });
    }

  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container-fluid">
  <div class="row">
    <div class="col">
      <div class="title">
        <h1>Twitch Monitor</h1></div>
    </div>
  </div>
  <div class="main">
    <div class="row stream-entry">
      <div class="col stream-title">
        Name
      </div>
      <div class="col stream-description">
        Playing
      </div>
    </div>
  </div>
</div>

0 个答案:

没有答案