【发布时间】:2020-12-07 13:20:25
【问题描述】:
我在 php 中使用这个 jquery 脚本来为每个循环模式添加一个唯一的 id。
除了我不明白为什么 $count 的 var myVideo=document.getElementById('htmlVideo' + <?php echo $count?>); 总是返回 6 时,一切都运行良好
假设我要点击 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">×</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>
<script>
var container = $("#htmlVideo<?php echo $count?>");
var myVideo=document.getElementById('htmlVideo' + <?php echo $count?>);
$(document).ready(function(){
$("#videoBtn<?php echo $count?>").click(function(){
console.log(myVideo);
myVideo.play();
});
$("#videoModal<?php echo $count?>").click(function(e)
{
// if the target of the click isn't the container nor a descendant of the container
if (!container.is(e.target) && container.has(e.target).length === 0)
{
myVideo.pause();
}
});
});
</script>
</div>
</div>
</div>
</div>
<?php
$count++;
endwhile;
?>
【问题讨论】:
-
循环脚本是非常糟糕的做法。给视频一个类,并通过一个脚本使用该类来访问它——这意味着你甚至不需要给它一个 ID
-
这会覆盖所有其他变量
var myVideo=document.getElementById('htmlVideo' + <?php echo $count?>); -
@mplungjan 如何在我仍然想合并 $count 的同时做到这一点?
标签: php jquery wordpress advanced-custom-fields