2014-01-21 2 views
1

성능 향상을 위해 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과 논리를 파악해야 ...

추신 : 그 코드는 그 목적이 매우 오래 걸릴 수도 있습니다. 한 번 클릭 할 때마다 다음 3 개 이하의 동영상 만로드해야합니다. 나는 그것이 더 잘 쓰여질 수 있다고 생각하지만, 변수가 정의되지 않은 이유를 알아 낸 후에 만 ​​작업하겠습니다.

편집 : 그건 그렇고, 전체 코드는 $ (document) .ready 함수 안에 있습니다. 그에 따라 코드 거주를 변경했습니다.

+3

[함수 영역 (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions#Function_scope). – Teemu

답변

1

최상의 솔루션은 함수 범위 (정의한 변수는 함수 외부에서 사용할 수 없음)를 벗어날뿐만 아니라 getJSON이 비동기이며 즉시 결과를 반환하지 않는다는 것을 명심해야합니다.

내 조언 :

편집 : 당신은 당신이 항상 3 개 동영상이 없습니다 추가하기 때문에, 내가 당신을 위해 그것을 단순화 : 지금은 비디오가 존재하고 추가 점검이 경우 getJSON 응답의 클릭 핸들러를 첨부 만약 사실이라면, 그것은 생략됩니다. 여러 번 클릭 할 때

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 && currentvid2 && currentvid3){ 
      $('#inputvids').append(currentvid1 + currentvid2 + currentvid3); 
      vidIndex += 3; 
     }else if(currentvid1 && currentvid2){ 
      $('#inputvids').append(currentvid1 + currentvid2); 
      $('#showmorebtn').remove(); 
     }else if(currentvid1){ 
      $('#inputvids').append(currentvid1); 
      $('#showmorebtn').remove(); 
     }else { 
      $('#showmorebtn').remove(); 
     } 
    }); 
}); 

는 코드의 더 나은 버전이 실제로 작동합니다 : (전역이 vidIndex 업데이트가 실제로 클릭에 변화를 만들어, 지역 주민을 제거하고, 기능 범위 지금 - 이전 스크립트가 단지 추가를 세 다음 동영상 몇번)

$.getJSON("js/videos.json", function(data) { 
    var videosArr = []; 
    var vidIndex = 0; 

    $.each(data, function(key, val) { 
     videosArr.push('<iframe width="315" height="236" src="'+val+'" frameborder="0" allowfullscreen></iframe>'); 
    }); 

    $('#showmorebtn').click(function(){ 
     if (videosArr[vidIndex] && videosArr[vidIndex+1] && videosArr[vidIndex+2]){ 
      $('#inputvids').append(videosArr[vidIndex] + videosArr[vidIndex+1] + videosArr[vidIndex+2]); 
      vidIndex += 3; 
     }else if(videosArr[vidIndex] && videosArr[vidIndex+1]){ 
      $('#inputvids').append(videosArr[vidIndex] + videosArr[vidIndex+1]); 
      $('#showmorebtn').remove(); 
     }else if(videosArr[vidIndex]){ 
      $('#inputvids').append(videosArr[vidIndex]); 
      $('#showmorebtn').remove(); 
     }else { 
      $('#showmorebtn').remove(); 
     } 
    }); 
}); 
+0

이 경우 showmorebtn은 항상 표시되며 시작 부분에는 아무런 반응이 없습니다. 처음에 버튼을 숨기고 $ ('# showmorebtn'). show()를 추가하여 동작을 첨부 한 후 표시 할 수 있습니다. – MrP

+0

"여전히 정의되지 않은 속성 길이 '를 읽을 수 없습니다. 그건 그렇고, 전체 코드는 $ (document) .ready 함수 안에 있습니다. – user2816581

+0

여전히 undefined 속성을 반환하는 경우 currentvid 변수를 할당 할 때 배열의 범위를 벗어나기 때문입니다. videosArr [vidIndex + 2]이 (가) 확실합니까? (또는 오타를 만들지 않았다) – MrP

관련 문제