代码如下,但我得到“ytplayer未定义”错误。这是
的问题<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);
返回一个对象,但在loadNewVideo中调用alert(ytplayer);
会返回null。
这是直接从http://code.google.com/apis/youtube/chromeless_example_1.html复制的,它可以正常工作。我出错的任何想法?是否在对象上调用getElementById?
答案 0 :(得分: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();
}