我已经得到了这个代码基本上..点击一个div,它会加载段落并将其插入到twitch api url中。该脚本应该正常工作,但是在fadeOut之后,div仍然是空的。控制台返回twitchData未定义的错误,但确实如此。 所以它应该这样工作:点击div - >了解点击了哪个div - < fadeOut + empty()div - >得到段落文本 - >在twitchApi链接等内部替换它。
$('.games > div').click((e) => {
var gameDiv = $(this); // Get which div was clicked here
$('#twitch').children().fadeOut(500).promise().then(function() {
$('#twitch').empty();
$(function() {
var i = 0;
var gameName = $(e.target).text().replace(' ', '%20'); // Get the game name
console.log(gameName);
var twitchApi = "https://api.twitch.tv/kraken/streams?game=" +gameName; // Build the URL here
var twitchData;
$.getJSON(twitchApi, function(json) {
twitchData = json.streams;
setData()
});
});
function setData() {
var j = twitchData.length > (i + 9) ? (i + 9) : twitchData.length; for (; i < j; i++) {
var streamGame = twitchData[i].game;
var streamThumb = twitchData[i].preview.medium;
var streamVideo = twitchData[i].channel.name;
var img = $('<img style="width: 250px; height: 250px;" src="' + streamThumb + '"/>');
$('#twitch').append(img);
img.click(function() {
$('#twitch iframe').remove()
$('#twitch').append( '<iframe style="width: 600px;" src="http://player.twitch.tv/?channel=' + streamVideo + '"></iframe>');
});
}
}
$('#load').click(function() {
setData();
});
});
});
答案 0 :(得分:1)
这是一个范围问题。你需要传递'twitchData&#39;进入你的setData函数。现在它只在您的点击事件中定义。
$('.games > div').click((e) => {
var gameDiv = $(this); // Get which div was clicked here
$('#twitch').children().fadeOut(500).promise().then(function() {
$('#twitch').empty();
$(function() {
var i = 0;
var gameName = $(e.target).text().replace(' ', '%20'); // Get the game name
console.log(gameName);
var twitchApi = "https://api.twitch.tv/kraken/streams?game=" +gameName; // Build the URL here
$.getJSON(twitchApi, function(json) {
setData(json.streams)
});
});
function setData(twitchData) {
var j = twitchData.length > (i + 9) ? (i + 9) : twitchData.length; for (; i < j; i++) {
var streamGame = twitchData[i].game;
var streamThumb = twitchData[i].preview.medium;
var streamVideo = twitchData[i].channel.name;
var img = $('<img style="width: 250px; height: 250px;" src="' + streamThumb + '"/>');
$('#twitch').append(img);
img.click(function() {
$('#twitch iframe').remove()
$('#twitch').append( '<iframe style="width: 600px;" src="http://player.twitch.tv/?channel=' + streamVideo + '"></iframe>');
});
}
}
});
});