1

コードは次のとおりですが、「ytplayer is not defined」というエラーが表示されます。これは問題ですか

<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);機能し、この関数内ではオブジェクトが返されますが、alert(ytplayer);loadNewVideo 内で呼び出すと null が返されます。

これはhttp://code.google.com/apis/youtube/chromeless_example_1.htmlから直接コピーされ、問題なく動作します。私が間違っているアイデアはありますか?オブジェクトで getElementById を呼び出すことと関係がありますか?

4

1 に答える 1

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(); 
} 
于 2009-07-03T16:34:14.483 に答える