Youtube API - 使用"这个"播放当前视频

时间:2015-12-01 02:24:32

标签: javascript jquery css3 youtube-api

我正在使用youtube API并且我想播放点击的当前视频并将其停止但我的问题是我为每个视频使用相同的ID并且我想使用选择器#34;这个"播放或停止当前视频,但我不知道该怎么做。

这是我的代码:



<script src="https://www.youtube.com/iframe_api"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>

<div class="embeded-video">
  <iframe id="player" type="text/html" width="348" height="196"
    src="http://www.youtube.com/embed/M7lc1UVf-VE?enablejsapi=1&fs=0&showinfo=0&rel=0"
    frameborder="0"></iframe>
</div>
<div class="controls">
  <input type="button" value="Play" onclick="play();">
  <div id="stop">Stop</div>
</div>

<div class="embeded-video">
  <iframe id="player" type="text/html" width="348" height="196"
    src="http://www.youtube.com/embed/M7lc1UVf-VE?enablejsapi=1&fs=0&showinfo=0&rel=0"
    frameborder="0"></iframe>
</div>
<div class="controls">
  <input type="button" value="Play" onclick="play();">
  <div id="stop">Stop</div>
</div>

<script>
  $(document).ready(function(){
  	$("#stop").click(function(){
  		var video = $(this).closest(".controls").prev().find("#player").attr("src");
  		$(this).closest(".controls").prev().find("#player").attr("src","");
  		$(this).closest(".controls").prev().find("#player").attr("src",video);
	});
  });

  var player;
  function onYouTubeIframeAPIReady() {
    player = new YT.Player('player');
  }
  function play(){
    player.playVideo();
    player.setVolume(100);
  }
</script>
&#13;
&#13;
&#13;

有人可以帮我吗?

1 个答案:

答案 0 :(得分:0)

this这样的东西可以帮到你。基本上我已经制作了一个通用代码,需要将视频容器div添加到您的代码中,以识别每个视频的容器并播放或停止特定视频。

var players = {};
function onYouTubeIframeAPIReady() {
  $('.player').each(function(){
      var $this = $(this);
      var playerId = $this.attr('id');
      players[playerId] = new YT.Player(playerId);
  });
}
$('.play').click(function(){
  var $this = $(this);
  var currentPlayer = $this.parents('.video-container').find('.player');
  players[currentPlayer.attr('id')].playVideo();
});
$('.stop').click(function(){
  var $this = $(this);
  var currentPlayer = $this.parents('.video-container').find('.player');
  players[currentPlayer.attr('id')].stopVideo();
});