【问题标题】:Youtube API - Use "this" to play the current videoYoutube API - 使用“this”播放当前视频
【发布时间】:2015-12-01 02:24:31
【问题描述】:

我正在使用 youtube API,我想播放当前点击的视频并停止它,但我的问题是我为每个视频使用相同的 ID,我想使用选择器“this”播放或停止当前视频,但我不知道该怎么做。

这是我的代码:

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

有人可以帮我吗?

【问题讨论】:

    标签: javascript jquery css youtube-api


    【解决方案1】:

    也许像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();
    });
    

    【讨论】:

    • 谢谢,我去看看
    猜你喜欢
    • 2013-12-15
    • 1970-01-01
    • 2018-10-12
    • 1970-01-01
    • 1970-01-01
    • 2020-05-11
    • 2015-12-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多