2009-07-03 24 views
1

代碼如下,但我得到「ytplayer is not defined」錯誤。這是「ytplayer未定義」使用SWFObject方法在網站上包含無鉻Youtube視頻

<script src="http://www.google.com/jsapi"></script> 
<script> 
    google.load("swfobject", "2.1"); 
</script> 

<script type="text/javascript"> 

     function updateHTML(elmId, value) { 
      document.getElementById(elmId).innerHTML = value; 
     } 

     function setytplayerState(newState) { 
      updateHTML("playerstate", newState); 
     } 

     function onYouTubePlayerReady(playerId) { 
      ytplayer = document.getElementById("myytplayer"); 
      ytplayer.addEventListener("onStateChange", "onytplayerStateChange"); 
      ytplayer.addEventListener("onError", "onPlayerError"); 
     } 

     function onytplayerStateChange(newState) { 
      setytplayerState(newState); 
     } 

     function onPlayerError(errorCode) { 
      alert("An error occured: " + errorCode); 
     } 

     // functions for the api calls 
     function loadNewVideo(id, startSeconds) { 
      if (ytplayer) { 
      ytplayer.loadVideoById(id, parseInt(startSeconds)); 
      } 
     } 

     function play() { 
      if (ytplayer) { 
      ytplayer.playVideo(); 
      } 
     } 


    </script> 

其插入此處

<div id="ytapiplayer"> 

</div> 
<script type="text/javascript"> 
     // <![CDATA[ 

     // allowScriptAccess must be set to allow the Javascript from one 
     // domain to access the swf on the youtube domain 
     var params = { allowScriptAccess: "always", wmode: "transparent", menu: "false" }; 
     // this sets the id of the object or embed tag to 'myytplayer'. 
     // You then use this id to access the swf and make calls to the player's API 
     var atts = { id: "myytplayer" }; 
     swfobject.embedSWF("http://www.youtube.com/apiplayer?enablejsapi=1&playerapiid=ytplayer", 
         "ytapiplayer", "100%", "100%", "8", null, null, params, atts); 
     loadNewVideo('11mrMppgfrQ','0'); 
     play(); 
//]]> 
    </script> 

onYouTubePlayerReady作品和alert(ytplayer);在這個函數返回一個對象,但是調用內loadNewVideo alert(ytplayer);返回null的問題。

這是從http://code.google.com/apis/youtube/chromeless_example_1.html直接複製它工作正常。任何想法,我要去錯了嗎?它是否與在對象上調用getElementById相關?

+0

對不起,刪除了dupe – ewengcameron 2009-07-03 16:33:12

回答

1

發現問題。

loadNewVideo('11mrMppgfrQ','0'); 
     play(); 

分別致電之前

function onYouTubePlayerReady(playerId) { 
     ytplayer = document.getElementById("myytplayer"); 
     ytplayer.addEventListener("onStateChange", "onytplayerStateChange"); 
     ytplayer.addEventListener("onError", "onPlayerError"); 
    } 

移動它們的功能中,以這條線後

ytplayer = document.getElementById("myytplayer"); 

固定問題

最終代碼如下所示:

function onYouTubePlayerReady(playerId) { 
    ytplayer = document.getElementById("myytplayer"); 
    ytplayer.addEventListener("onStateChange", "onytplayerStateChange"); 
    ytplayer.addEventListener("onError", "onPlayerError"); 
    loadNewVideo('11mrMppgfrQ','0'); 
    play(); 
}