2014-12-05 2 views
0

작은 텍스트 기반 게임을 만들고 있는데 Youtube-embed을 통해 배경 음악을 통합하려고합니다. 아마 없을 최고의 솔루션,하지만 내 목표를 위해 작동합니다 :)innerHTML이 if/else에서 작동하지 않습니다.

이 같은 구축 여러 데이터 수집과 구축 자바 스크립트 데이터베이스있다 : 나는 데이터베이스에서 콘텐츠를

{ 
     "question":"blabla.", 
     "answers":[ 
      {"title":"Left","response":3}, 
      {"title":"Right","response":2} 
      ], 
     "youembed":"<iframe id='youtube' width='100' height='100' src='http://www.youtube.com/embed/VIIOVtWGSj8?autoplay=1' frameborder='0' allowfullscreen></iframe>" 
    }, 

를 배치 다음 조각 내 HTML : db[currentLocation].youembed의 길이 인 경우

document.getElementById("question").innerHTML = db[currentLocation].question; 

그러나, 나는에만 youembed 실제로 HTML에 배치 할

이상

그래서 내가 쓴 다음 나는 경우 문의 document[..].youembed 외부를 사용할 때마다

if (youembed > 0) { 
    document.getElementById("youembed").innerHTML = db[currentLocation].youembed;   
} 

, 그러나, 나는 그것이 경우 문에서 작동하려면, 문제없이 작동, 그래서 '아무튼 db[currentLocation].youembed이> 0 일 때까지 현재 재생중인 노래를 바꿉니다.

무엇이 잘못 되었나요? 나는 alert(youembed)을 코드에 넣었습니다. 그래서 길이를 볼 수 있고, 그 중 하나가 0 인 것을 보여주고, 2 페이지의 다른 것은 145이지만, 그 경우에는 if -statement를 실행하지 않습니다. 여기

는 전체 자바 스크립트 코드입니다 :

var currentLocation = 0; 

window.printCurrentLocation = function(){ 
    document.getElementById("question").innerHTML = db[currentLocation].question; 
    var youembed = db[currentLocation].youembed; 
    alert(youembed.length); 
    if (youembed > 0) { 
     document.getElementById("youembed").innerHTML = db[currentLocation].youembed;   
    } 
    else { 

    } 

    var answers = ""; 
    for(var i=0,l=db[currentLocation].answers.length;i<l;i++){ 
     answers += "<p><button onclick='setLocation("+db[currentLocation].answers[i].response+")'>"+db[currentLocation].answers[i].title+"</button></p>"; 
    } 
    document.getElementById("answers").innerHTML = answers; 
} 

window.setLocation = function(num) { 
    currentLocation = num; 
    window.printCurrentLocation(); 
} 

window.printCurrentLocation(); 

답변

1

당신은

if(youembed.length){ 
    ... 
} 
+0

나는'youembed' 변수를 설정하는 것을 잊어 버렸습니다. 추가 된 Javascript 코드를 확인하십시오! :) – Rvervuurt

+0

@Rvervuurt - 네, 그걸 보았습니다 대답은 – Jamiec

+1

오, 물론 나는 또한 if 문에서 길이를 확인해야합니다! :/ 고마워 – Rvervuurt

1

당신은 길이를 비교하지 않는 사용해야해야 여기

if (youembed > 0) { ... } 

이 권리

if (youembed.length > 0) { ... } 

예제 코드 : http://jsfiddle.net/f7cedqrf/

관련 문제