我編寫了一個腳本來加載帶有JSON請求的視頻以提高性能,但我無法使其正常工作。奇怪的是,console.log(currentvid1)返回正確的值,但函數一直說currentvid1未定義。變量在控制檯中返回正確的值,但未定義
我想訣竅應該是按部分代碼的順序,但是在嘗試將它們移動到這裏和那裏之後,我就更加困惑了。這是在當前狀態下的代碼:
$(document).ready(function(){
var videosArr = [];
var vidIndex = 0;
$.getJSON("js/videos.json", function(data) {
$.each(data, function(key, val) {
videosArr.push('<iframe width="315" height="236" src="'+val+'" frameborder="0" allowfullscreen></iframe>');
});
var currentvid1 = videosArr[vidIndex];
var currentvid2 = videosArr[vidIndex+1];
var currentvid3 = videosArr[vidIndex+2];
$('#showmorebtn').click(function(){
if (currentvid1.length > 0 && currentvid2.length > 0 && currentvid3.length > 0){
$('#inputvids').append(currentvid1 + currentvid2 + currentvid3);
vidIndex += 3;
}else if(currentvid1.length > 0 && currentvid2.length > 0 && currentvid3.length == 0){
$('#inputvids').append(currentvid1 + currentvid2 + currentvid3);
$('#showmorebtn').remove();
}else if(currentvid1.length > 0 && currentvid2.length == 0){
$('#inputvids').append(currentvid1);
$('#showmorebtn').remove();
}else if(currentvid1.length > 0){
$('#inputvids').append(currentvid1);
$('#showmorebtn').remove();
}else if(currentvid1.length == 0){
$('#showmorebtn').remove();
}
});
});
});
也許這代碼不接近正確的一些那些我嘗試過的,但無論如何...我只需要找出與JSON邏輯...
PS:此外代碼可能看起來非常長,其目的。每次點擊只需加載3個或更少的視頻。我想它可以寫得更好,但是我只會在弄清楚爲什麼變量返回undefined後才能處理它。
編輯:順便說一下,整個代碼是$(document).ready函數的內部。我已經相應地更改了代碼。
[功能範圍(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions#Function_scope)。 – Teemu