我试图用新的视频 ID 更改数据视频​​属性,但它没有改变

The data-video attribute I am trying to change with new video id but it is not changing

我试图将视频 ID 8IYzyTYucKQ 动态更改为 WKV_z36pVAk 但它没有改变。

我认为下面的库仅在页面重新加载时有效,所以当我单击按钮时,新的 ID 发生变化,但视频播放旧的 Id,当我再次重新加载视频时,Id 重置为默认值。

<!DOCTYPE html> 
    <html> 
    <head> 
    <meta charset="utf-8" /> 
    <title>About</title>
         <script type="text/javascript">
          function val1(val)
          {
        location.reload();
        document.getElementsByTagName("div")[0].setAttribute("data-video", val);
            //document.getElementById("youtube-audio").data-video=val;
            //document.getElementById("p1").innerHTML=val;
            alert(val);


          }

         </script>
    </head> 
    <body> 
    <h3 style="color:#0066dd">Hello</h3>

    <center>


    <div data-video="8IYzyTYucKQ"
         data-autoplay="0"
         data-loop="1"
         id="youtube-audio">
    </div> 

    </center>
    <button onclick="val1('WKV_z36pVAk')">change</button>


    </body> 
    <script src="https://www.youtube.com/iframe_api"></script>
    <script src="https://cdn.rawgit.com/labnol/files/master/yt.js"></script>
    </html>

您在使用更改数据属性后重新加载页面:

location.reload();

什么 returns 当页面刷新并再次准备时该属性为默认值。

使用API的简单示例:

<!DOCTYPE html>
<html>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script src="https://www.youtube.com/iframe_api"></script>
  </head> 
  <body>
    <h3 style="color:#0066dd">Hello</h3>
    <button id="change_video">change</button>
    <div id="player"></div>

    <script>
      var player;
      function onYouTubeIframeAPIReady() {
        player = new YT.Player('player', {
          height: '360',
          width: '640',
          videoId: 'M7lc1UVf-VE'
        });
      }

      $('#change_video').on('click', function(){
        player.loadVideoById('WKV_z36pVAk');
      })
    </script>

  </body>
</html>

希望对您有所帮助。