Javascript作用域 Youtube嵌入测试 函数onYouTubePlayerReady(playerid) { ytplayer=document.getElementById(“myytplayer”); } 函数名为player() { var params={allowScriptAccess:“始终”}; var atts={id:“myytplayer”}; swfobject.embeddeswf(“http://www.youtube.com/apiplayer?enablejsapi=1", “ytapiplayer”、“1024”、“768”、“8”、空、空、参数、atts); } 功能加载视频(id,开始) { ytplayer.loadVideoById(id,start); } 您需要启用Flash player 8+和JavaScript才能查看此视频。

Javascript作用域 Youtube嵌入测试 函数onYouTubePlayerReady(playerid) { ytplayer=document.getElementById(“myytplayer”); } 函数名为player() { var params={allowScriptAccess:“始终”}; var atts={id:“myytplayer”}; swfobject.embeddeswf(“http://www.youtube.com/apiplayer?enablejsapi=1", “ytapiplayer”、“1024”、“768”、“8”、空、空、参数、atts); } 功能加载视频(id,开始) { ytplayer.loadVideoById(id,start); } 您需要启用Flash player 8+和JavaScript才能查看此视频。,javascript,Javascript,我是Javascript新手,所以我很难让它正常工作。调试器告诉我函数loadVideo()中未定义ytplayer。为什么会这样?我知道在大括号结束时,onYouTubePlayerReady中声明的变量超出了范围。那么如何访问loadVideoById方法呢?更让我困惑的是,我可以做这样的事情: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xh

我是Javascript新手,所以我很难让它正常工作。调试器告诉我函数loadVideo()中未定义ytplayer。为什么会这样?我知道在大括号结束时,onYouTubePlayerReady中声明的变量超出了范围。那么如何访问loadVideoById方法呢?更让我困惑的是,我可以做这样的事情:

<!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>

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

<a href="javascript:void(0);" onclick="ytplayer.loadVideoById('e1h5TzdTq0o', 0);">test</a>
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 );
}