1

當我加載YouTube視頻加載時的回調,onYouTubePlayerReady,在jQuery就緒函數中,當視頻加載時不會調用它。但是,當我將回調放在jQuery就緒函數之外時,它被調用。我怎樣才能修復它,以便我可以把回調放入jQuery函數中。下面的代碼。謝謝。使用jQuery和YouTube API加載事件

<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的網址,http://swfobject.googlecode.com/svn/trunk/swfobject/swfobject.js的情況下,它可以幫助

回答

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> 
+0

工作!我想'onYouTubePlayerReady'準備就緒,所以我可以從裏面做jQuery的東西。我很好奇,爲什麼它的工作。 「這取決於什麼時候建立了youtubeplayer引用指針關聯」,它是什麼意思 – Alexis 2012-04-15 01:27:41

+0

它的工作原理是因爲我們將函數分配給了全局變量「onYouTubePlayerReady」--YT API掛鉤的全局變量。 (在你的準備好的處理程序之外沒有任何私人功能可以定位) - 我擔心YT API可能會在我們分配它之前將指針設置爲全局「onYouTubPlayerReady」變量,並且可能有問題。很高興它的工作。 – webnesto 2012-04-15 01:49:32

+1

使用'window.onYouTubePlayerReady = ...',或者在'$()。ready'處理程序之外添加'var onYouTubePlayerReader;'。否則,您將爲未聲明的全局變量賦值。這個功能非常糟糕,以至於在嚴格模式下被禁止(請參閱:http://jsfiddle.net/WNtmV/)。 – 2012-04-15 09:28:10