猿问

通过 php 变量使用 getElementById

我在 php 中使用这个 jquery 脚本向每个循环模式添加一个唯一的 id。

事情是一切都工作得很好,除了我不明白为什么$countforvar myVideo=document.getElementById('htmlVideo' + <?php echo $count?>);总是在说 6 时返回 a

假设我要单击 videoBtn1,#videoModal1 将打开正确的视频,但 myVideo 将从 #htmlVideo6 返回视频。无论我点击 videoBtn1 还是 videoBtn10,myVideo 始终指向 #htmlVideo6

<?php  

  $count = 0;

  while ( have_rows('video') ) : the_row(); ?>

    <div class="col-lg-4 col-md-6 mt-3 mt-lg-5">

      <div class="d-flex flex-column h-100 px-3">

        <div data-toggle="modal" data-target="#videoModal<?php echo $count?>" id="videoBtn<?php echo $count?>">

           <img src="<?php echo get_sub_field('video_thumbnail') ?> " width="100%" style="height: 240px;object-fit: cover;">

        </div>


        <div class="py-3 h-100 d-flex flex-column align-items-start">

          <h4 class="text-heavy">

            <?php echo get_sub_field('title') ?>

          </h4>

          <p>

              <?php echo get_sub_field('content') ?>

          </p>

        </div>


      </div>

    </div>

    <!--Video Modal -->

    <div class="modal fade" id="videoModal<?php echo $count?>" role="dialog" aria-labelledby="videoModal<?php echo $count?>Label" aria-hidden="true" >

      <div class="modal-dialog modal-lg" role="document">

        <div class="modal-content">

          <div class="modal-body p-3 position-relative">


            <div type="button" class="close" data-dismiss="modal" aria-label="Close">

              <span aria-hidden="true" class="text-white">&times;</span>

            </div>

            <video id="htmlVideo<?php echo $count?>" width="100%" controls style="z-index:5">

              <source src="<?php echo get_sub_field('video')?>" type="video/mp4">

            </video>


精慕HU
浏览 107回答 2
2回答

饮歌长啸

循环脚本是非常糟糕的做法。为按钮和/或视频指定一个类,并使用该类通过一段脚本来访问它 - 这意味着您甚至不需要为其提供 ID这每次都会覆盖所有其他变量var myVideo=document.getElementById('htmlVideo' + <?php echo $count?>);尝试这个:给父容器一个类:<div class="modalClickParent col-lg-4 col-md-6 mt-3 mt-lg-5">并使用类似的东西$(function() {&nbsp; $("[data-toggle=modal]").on("click", function() {&nbsp; &nbsp; const myVideo = $(this).closest(".modalClickParent").next().find("video").get(0);&nbsp; &nbsp; if (!$(this).data("playing")) {&nbsp; &nbsp; &nbsp; myVideo.play();&nbsp; &nbsp; &nbsp; $(this).data("playing", true);&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; myVideo.pause();&nbsp; &nbsp; &nbsp; $(this).data("playing", false);&nbsp; &nbsp; }&nbsp; });});

至尊宝的传说

只需创建一个要单击的类并为其指定 data-id 属性在 jquery 部分使用类似的代码$('.class').click(function(){<bR>&nbsp; &nbsp; var that=$(this);<bR>&nbsp; &nbsp; var id=that.data('id');<bR>&nbsp; &nbsp; //now do your stuff here like<bR>&nbsp; &nbsp; $('#div'+id).modal('show');<bR>});
随时随地看视频慕课网APP
我要回答