使用 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(); 

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



慕雪6442864
浏览 112回答 1
1回答

小怪兽爱吃肉

您可以在不需要 ID 属性的情况下完成特定视频的定位,而是使用querySelectorAll和querySelector(您也可以使用父/子/兄弟遍历技术)如果您创建一个nodelistusing ,querySelectorAll您可以在外部分配事件侦听器而不是使用<a onclick='play()'>etc ,这是首选方法。该click事件已注册为您可以发出另一个查询以查找使用this的子元素thisquerySelector<?php&nbsp; &nbsp; include("conn.php");&nbsp; &nbsp; $sql = mysqli_query($con, "SELECT * FROM uploads ORDER BY file_id DESC");&nbsp; &nbsp; while ($row = mysqli_fetch_array($sql)) {&nbsp; &nbsp; &nbsp; &nbsp; $path = $row['path'];&nbsp; &nbsp; &nbsp; &nbsp; $caption = $row['caption'];?><div class="responsive">&nbsp; <div class="gallery">&nbsp; &nbsp; <a href="#">&nbsp; &nbsp; &nbsp; <video&nbsp; width="600" height="400">&nbsp; &nbsp; &nbsp; &nbsp; <source src="store/vids/<?php echo $path;?>" type="video/mp4">&nbsp; &nbsp; &nbsp; </video>&nbsp; &nbsp; </a>&nbsp; &nbsp; <div class="desc"><br><?php echo $caption?> <span class="badge badge-pill badge-primary">Trending</span></div>&nbsp; </div></div><?php&nbsp;&nbsp; &nbsp; }//close while loop?><script>&nbsp; &nbsp; Array.from( document.querySelectorAll('.gallery > a') ).forEach( a=>{&nbsp; &nbsp; &nbsp; &nbsp; a.addEventListener('click',function(e){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var video=this.querySelector('video');&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if( video.paused )video.play();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; else video.pause();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // find other videos that are NOT the one just activated and pause them&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Array.from( document.querySelectorAll('.gallery > a > video') ).forEach( el=>{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if( el!=video )el.pause()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; })&nbsp; &nbsp; &nbsp; &nbsp; })&nbsp; &nbsp; })</script>
打开App,查看更多内容
随时随地看视频慕课网APP