2011-04-25 100 views
0
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 

<html xmlns="http://www.w3.org/1999/xhtml"> 

<head> 
    <title>Youtube embed test</title> 
    <script type="text/javascript" src="swfobject/swfobject.js"></script> 
    <script type="text/javascript"> 
     function onYouTubePlayerReady(playerid) 
     { 
      ytplayer = document.getElementById("myytplayer"); 
     } 

     function embedPlayer() 
     { 
      var params = { allowScriptAccess: "always" }; 
      var atts = { id: "myytplayer" }; 
      swfobject.embedSWF("http://www.youtube.com/apiplayer?enablejsapi=1", 
         "ytapiplayer", "1024", "768", "8", null, null, params, atts); 
     } 

     function loadVideo(id, start) 
     { 
      ytplayer.loadVideoById(id, start); 
     } 
    </script> 
</head> 

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

    <a href="javascript:void(0);" onclick="loadVideo('bBObeZ6Vj3A',2);">Load</a> 

</body> 
</html> 

我是Javascript新手,因此无法使用此工具。调试器告诉我,函数loadVideo()中未定义ytplayer。为什么是这样?我知道在大括号结束时,onYouTubePlayerReady中声明的变量超出了范围。那么我怎样才能访问loadVideoById方法?我进一步困惑的是,我可以这样做:Javascript范围

<a href="javascript:void(0);" onclick="ytplayer.loadVideoById('e1h5TzdTq0o', 0);">test</a> 

事实证明,这是完全合法的。但为什么我允许使用ytplayer?我假设它与YouTubePlayerReady上的回调函数有关?

回答

0
function onYouTubePlayerReady() // playerid is usefull here or not 
{ 
    ytplayer = document.getElementById("myytplayer"); 
    return ytplayer; 
} 


function loadVideo(id, start) 
{ 
    ytplayer = onYouTubePlayerReady(); // call onYouTubePlayerReady to get the object of ytplayer 
    ytplayer.loadVideoById(id, start); 
}