2

我试图简单地创建一个可以使用 iFrame API 控制 YouTube 视频的菜单。我在 id="pause_button" 的 HTML 中放置了一个按钮,并尝试使用 jquery 创建一个函数,以便在单击时暂停视频。下面是我的 HTML 文档:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>Untitled 1</title>
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">

  // 2. This code loads the IFrame Player API code asynchronously.
  var tag = document.createElement('script');
  tag.src = "//www.youtube.com/iframe_api";
  var firstScriptTag = document.getElementsByTagName('script')[0];
  firstScriptTag.paresntNode.insertBefore(tag, firstScriptTag);

  // 3. This function creates an <iframe> (and YouTube player)
  //    after the API code downloads.
  var player;
  function onYouTubeIframeAPIReady() {
    player = new YT.Player('player', {
      events: {
        'onReady': onPlayerReady,
        'onStateChange': onPlayerStateChange
      }
    });
  }

  // 4. The API will call this function when the video player is ready.
  function onPlayerReady(event) {
    event.target.playVideo();
  }

  // 5. The API calls this function when the player's state changes.
  //    The function indicates that when playing a video (state=1),
  //    the player should play for six seconds and then stop.
  var done = false;
  function onPlayerStateChange(event) {
    if (event.data == YT.PlayerState.PLAYING && !done) {
      setTimeout(stopVideo, 6000);
      done = true;
    }
  }
  function stopVideo() {
    player.stopVideo();
  }

</script>
<script type="text/javascript">
$(document).ready(function(){
    $("#pause_button").click(function(){
        $("#test").append("TEST");
        player.pauseVideo();
    });
});
</script>

</head>
  <body>
    <!-- 1. The <iframe> (and video player) will replace this <div> tag. -->
    <iframe id="player" type="text/html" width="640" height="390" src="http://www.youtube.com/embed/u1zgFlCw8Aw?enablejsapi=1&origin=http://example.com" frameborder="0">
    </iframe>

    <button id="pause_button">STOP</button>
    <div id="test">TEST<br /></div>
  </body>
</html>
4

1 回答 1

1

您的第一个错误,即无法调用未定义的方法“insertBefore”,是由于您的代码中的拼写错误;应该:

firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

(你有 parsntNode。)

第二个错误是由于您对 iframe 的 URL 参数的来源;您留在了示例来源 (http://example.com),但它应该设置为您的代码正在运行的服务器的值。这是一种安全措施,允许您的脚本随后与播放器的方法进行交互。

于 2012-11-21T07:39:39.957 回答