使用 JavaScript 从数据库播放视频

Play a video from database using JavaScript

我正在制作一个允许用户登录和上传视频的视频共享网站。一切正常!问题是用js播放视频不行;相反,只播放第一个视频。这是我检索视频的代码 (php/html)

    <?php
    include("conn.php");
    $sql = mysqli_query($con, "SELECT * FROM uploads ORDER BY file_id DESC");
    while ($row = mysqli_fetch_array($sql)) {
      $path = $row['path'];
      $caption = $row['caption'];

  ?>
<div class="responsive">
  <div class="gallery">
    <a href="#" onclick="play()">
      <video  width="600" height="400" id="video">
        <source src="store/vids/<?php echo $path;?>" type="video/mp4">
      </video>
    </a>
    <div class="desc"><br><?php echo $caption?> <span class="badge badge-pill badge-primary">Trending</span></div>
  </div>
</div>
<?php  } ?>

脚本看起来像:

var video = document.getElementById("video"); 
function play() { 
  if (video.paused) 
    video.play(); 
  else 
    video.pause(); 
} 

这东西只播放我的数据库 table 中的 第一个视频 。欢迎任何答案,包括可以使工作更轻松的 js 库。

不需要ID属性,使用querySelectorAllquerySelector即可完成特定视频的定位(也可以使用parent/child/sibling遍历技术)

如果您使用 querySelectorAll 创建 nodelist,您可以在外部分配事件侦听器,而不是使用 <a onclick='play()'> 等,这是首选方法。 click 事件注册为 this,因此您可以发出另一个查询以使用 querySelector

查找 this 的子元素
<?php
    include("conn.php");
    $sql = mysqli_query($con, "SELECT * FROM uploads ORDER BY file_id DESC");
    while ($row = mysqli_fetch_array($sql)) {
        $path = $row['path'];
        $caption = $row['caption'];

?>

<div class="responsive">
  <div class="gallery">
    <a href="#">
      <video  width="600" height="400">
        <source src="store/vids/<?php echo $path;?>" type="video/mp4">
      </video>
    </a>
    <div class="desc"><br><?php echo $caption?> <span class="badge badge-pill badge-primary">Trending</span></div>
  </div>
</div>

<?php 
    }//close while loop
?>


<script>
    Array.from( document.querySelectorAll('.gallery > a') ).forEach( a=>{
        a.addEventListener('click',function(e){
            var video=this.querySelector('video');

            if( video.paused )video.play();
            else video.pause();

            // find other videos that are NOT the one just activated and pause them
            Array.from( document.querySelectorAll('.gallery > a > video') ).forEach( el=>{
                if( el!=video )el.pause()
            })
        })
    })
</script>