【问题标题】:javascript YoutubePlayer OnStateChange not firingjavascript YoutubePlayer OnStateChange 未触发
【发布时间】:2014-08-09 14:00:42
【问题描述】:

我遇到了 YouTube 播放器 OnStateChange 未触发的问题。我查看了其他帖子,但它们不太适合我的情况,因为我可能使用的是不同的(无铬 javascript)版本。

HTML:

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

Javascript:

var params = { allowScriptAccess: "always", wmode: "Opaque" };
var atts = { id: "player" };
swfobject.embedSWF("http://www.youtube.com/apiplayer?enablejsapi=1&version=3",
                   "ytapiplayer", "100%", "100%", "8", null, null, params, atts);

function onYouTubePlayerReady(playerId){
  player = document.getElementById("player");
}

我基本上复制了文档中的示例。那我就做吧

var player = document.getElementById('player');

我可以让它正常工作。但唯一的问题是当它改变状态时, OnStateChange 事件不会触发。代码是这样的。

document.getElementById('player').addEventListener('OnStateChange', 
  function(new_state){
     console.log(new_state);
  }
)

新状态从未被打印出来。我做错了吗? http://jsfiddle.net/8QtrC/1/

【问题讨论】:

  • 没有在 getElementById('player') 中使用的名为 player (id="ytapiplayer") 的元素
  • 我认为 javascript 在“ytapiplayer”下嵌入了一个对象(id = “player”,具体在 atts 中)。我可以调用该对象上的所有方法(id="player"),但 OnStateChange 从未被解雇。
  • 你可能是对的。添加一些可以运行的代码?
  • 我在 jsfiddle 上放了一些代码。但是视频没有加载。我认为 jsfiddle 可能会禁止它。
  • 我将在答案中放置一个工作示例。

标签: javascript youtube-api youtube-javascript-api


【解决方案1】:

这个例子适合我。

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/swfobject/2.2/swfobject.js"></script>

<body>

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

<script type="text/javascript">

    var params = { allowScriptAccess: "always" };
    var atts = { id: "myytplayer" };
    swfobject.embedSWF("http://www.youtube.com/v/Bl4Qne-RpcM?enablejsapi=1&playerapiid=myytplayer&version=3",
                       "ytapiplayer", "425", "356", "8", null, null, params, atts);

function onYouTubePlayerReady(playerId) {
  ytplayer = document.getElementById("myytplayer");
  ytplayer.addEventListener("onStateChange", "onytplayerStateChange");
}

function onytplayerStateChange(newState) {
   alert("Player's new state: " + newState);
}
  </script>
</body>

【讨论】:

  • 哦,这就是该函数的使用方式。太棒了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-06-09
  • 2014-09-22
  • 1970-01-01
  • 2013-08-20
  • 2020-09-18
  • 2014-04-09
相关资源
最近更新 更多