1

当我在加载 YouTube 视频时放置回调时onYouTubePlayerReady,在 jQuery 就绪函数中,加载视频时不会调用它。但是,当我将回调放在 jQuery 就绪函数之外时,它会被调用。如何修复它以便我可以将回调放在 jQuery 函数中。代码如下。

<html>
<body>

<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript" src="{{ STATIC_URL }}swfobject.js"></script>    

<script type="text/javascript">

  /// --> When I put onYouTubePlayerReady here it IS called  //
  function onYouTubePlayerReady(playerId) {
      ytplayer = document.getElementById("myytplayer");
      ytplayer.playVideo();
  }

  $(document).ready(function(){
      
       /// --> When I put onYouTubePlayerReady here it is NOT called //

       var params = { allowScriptAccess: "always" };
       var atts = { id: "myytplayer" };
       swfobject.embedSWF("http://www.youtube.com/v/UkhisRY3RRQ?version=3&enablejsapi=1","ytapiplayer", "800", "500", "8", null, null, params, atts);
});

</script>

   <div id="ytapiplayer">
       You need Flash player 8+ and JavaScript enabled to view this video.
   </div>
</body>
</html>

此外,这里是 swfobject 的 url, http: //swfobject.googlecode.com/svn/trunk/swfobject/swfobject.js以防万一。

4

1 回答 1

2

你必须让它全局可用——如果你把它放在你准备好的处理程序中,它的作用域就是那个处理程序。为什么你需要它?您需要访问范围?你可以试试这个,但我不确定它是否适合你——这取决于 youtubeplayer 引用指针关联何时建立:

<html>
<body>

<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript" src="{{ STATIC_URL }}swfobject.js"></script>    

<script type="text/javascript">

  $(document).ready(function(){

      onYouTubePlayerReady = function(playerId) {
          ytplayer = document.getElementById("myytplayer");
          ytplayer.playVideo();
      }

       var params = { allowScriptAccess: "always" };
       var atts = { id: "myytplayer" };
       swfobject.embedSWF("http://www.youtube.com/v/UkhisRY3RRQ?version=3&enablejsapi=1","ytapiplayer", "800", "500", "8", null, null, params, atts);
});

</script>

   <div id="ytapiplayer">
       You need Flash player 8+ and JavaScript enabled to view this video.
   </div>
</body>
</html>
于 2012-04-15T01:02:18.897 回答