api 次调用 运行 次意外

api calls are running unexpected number of times

我正在工作 twitch tv api.api 呼叫是否应该等于 streamer 中的元素数量 array.but 它是多个呼叫 times.u 可以在 codepen 上看到它。

jsfiddle linkhttps://jsfiddle.net/o48wwLdf/ html

javascript代码

$(document).ready(function() {
  var i;
  var streamers = ["ESL_SC2", "OgamingSC2", "cretetion", "freecodecamp", "storbeck", "habathcx", "RobotCaleb", "noobs2ninjas"];        //streamers array
  for (i = 0; i < streamers.length; i++) {
    jsoncall(streamers[i]);                            //calling function for api calls.
  }
});

function jsoncall(stream) {                            //function for api call
  $.getJSON('https://api.twitch.tv/kraken/streams/' + stream + '?callback=?', function(data) {
    if (data.stream === null) {                       //if channel is offline display offline
      $("p").append("<p>" + stream + "                                offline</p>");
    } else {                                    //if channel is online show what is he streaming.
      $("p").append("<p>" + stream + data.stream.game + "</p>");
    }
  });
}

当你这样做时:

$("p").append(...);

内容附加到页面上的每个<p> 元素。由于您在内容中添加了更多 <p> 元素,因此到处都是重复项。

Here's a forked version of your CodePen。我在主 <p> 元素中添加了一个 id。请注意,将 <p> 附加到 <p> 无论如何都没有意义; <p> 元素不能像其他 <p> 元素那样包含块级元素。但是浏览器允许它。所以,HTML:

<p id=main></p>

更新后的JavaScript:

function jsoncall(stream) {
  $.getJSON('https://api.twitch.tv/kraken/streams/' + stream + '?callback=?', function(data) {
    if (data.stream === null) {
      $("#main").append("<p>" + stream + "                                offline</p>");
    } else {
      $("#main").append("<p>" + stream + data.stream.game + "</p>");
    }
  });
}