通过PHP变量使用getElementById

问题描述

我正在PHP中使用此jquery脚本在每个循环模式中添加唯一的ID。

除了我不明白为什么$count的{​​{1}}总是返回6时,事情一切都很好,

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

var myVideo=document.getElementById('htmlVideo' + <?PHP echo $count?>);

解决方法

循环脚本是非常差的做法。给按钮和/或视频一个类,并使用一个脚本片段使用该类来访问它-这意味着您甚至不需要为其提供ID

这每次都会覆盖所有其他vars

var myVideo=document.getElementById('htmlVideo' + <?php echo $count?>);

尝试一下:

给父容器一个类:

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

并使用类似

$(function() {
  $("[data-toggle=modal]").on("click",function() {
    const myVideo = $(this).closest(".modalClickParent").next().find("video").get(0);
    if (!$(this).data("playing")) {
      myVideo.play();
      $(this).data("playing",true);
    } else {
      myVideo.pause();
      $(this).data("playing",false);
    }
  });
});
,

只需创建一个您要单击的类并为其提供data-id属性

在jquery部分中,使用类似

的代码
$('.class').click(function(){<bR>
    var that=$(this);<bR>
    var id=that.data('id');<bR>
    //now do your stuff here like<bR>
    $('#div'+id).modal('show');<bR>
});