如何将特定 ID 传递给嵌入式 YouTube 播放器

How do I pass specific ID to embedded YouTube player?

本文关键字:嵌入式 YouTube 播放器 ID      更新时间:2023-09-26

编辑: 我想出了更好的解决方案。在 while 循环中,我将 id 作为参数传递给 onclick 函数。但是,现在当我单击任何DIV没有任何反应。你能说出问题出在哪里吗?感谢您的帮助。

我遇到了一个问题。我正在尝试实现拖车。用户可以观看它们的方式是使用 javascript/jQuery 单击一个应该表现为按钮的div。问题是我只想有一个嵌入式播放,所以我不需要多次回收代码。但是我不知道如何让玩家播放刚刚点击按钮的电影预告片。 下面是代码,下面是我的请求摘要。感谢您的阅读。

//Trailer links that got generated with a loop..
//EDIT: DIVs now contain the id as an attribute to a onClick function
<div class="trailer" onclick="playTrailer(M7lc1UVf-VE)">
    <p>WATCH TRAILER</p>
</div>
<div class="trailer" onclick="playTrailer(ksfj34ln-Xe)">
    <p>WATCH TRAILER</p>
</div>
<div class="trailer" onclick="playTrailer(rasdasdl-Xe)">
    <p>WATCH TRAILER</p>
</div>
//EDIT: added hidden DIV that should be displayed when the DIVs are clicked
<div id="trailer-box" style="display: none;">
    //EDIT: the play is now within the hidden DIV
    <div id="ytplayer"></div>
</div>
<script>
  function showMovie(id){
      $('.trailer-box').toggle(); //EDIT: newly added
      var tag = document.createElement('script');
      tag.src = "https://www.youtube.com/player_api";
      var firstScriptTag = document.getElementsByTagName('script')[0];
      firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
      var player;
      function onYouTubePlayerAPIReady() {
        player = new YT.Player('ytplayer', {
          height: '390',
          width: '640',
          videoId: id
        });
      }
  }
</script>

我想知道是否有办法在单击DIV后检索其值并将其传递给脚本的videoId字段。如果你们中的任何人知道如何做到这一点,即使这意味着更多的调整,请告诉我。非常感谢您的阅读和回复。

看起来你没有使用 jQuery,所以:

您应该改用数据属性:

<div data-id="M7lc1UVf-VE" class="watch">
    <p>WATCH TRAILER for movie A</p>
</div>

然后:

var nodeList = document.querySelectorAll('.watch');
for (var i = 0; i < nodeList.length; i++) {
    nodeList[i].addEventListener('click', 
                    function(e){
                      showMovie(e.target.parentElement.getAttribute("data-id"));
                    }, 
                    false);
}
function showMovie(id){
  var tag = document.createElement('script');
  tag.src = "https://www.youtube.com/player_api";
  var firstScriptTag = document.getElementsByTagName('script')[0];
  firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
  var player;
  function onYouTubePlayerAPIReady() {
    player = new YT.Player('ytplayer', {
      height: '390',
      width: '640',
      videoId: id
    });
  }
}

应该是这样的

$('.watch').click (function (){
    player.loadVideoById($(this).attr ('id'));
});

更多信息