使用JavaScript播放数据库中的视频

问题描述 投票:0回答:1

我正在建立一个视频共享网站,允许用户登录和上传视频。一切正常!问题是,使用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(); 
} 

此内容仅播放我的数据库表中的第一个视频。欢迎任何答案,包括使工作变得更轻松的js库。

javascript php html video media
1个回答
0
投票

您可以使用querySelectorAllquerySelector来完成对特定视频的定位,而无需ID属性,也可以使用父/子/兄弟遍历技术)

如果使用nodelist创建querySelectorAll,则可以从外部分配事件侦听器,而不是使用<a onclick='play()'>等,这是首选方法。 click事件已注册为this,因此您可以使用this

发出另一个查询来查找querySelector的子元素。
<?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>
© www.soinside.com 2019 - 2024. All rights reserved.