>我有一个while循环,可以从数据库中选择多个图像。我有一个带有 href 的链接,单击它时有一个功能,它会打开一个视频模态框。现在,无论选择哪个链接,它都只选择第一个href链接。如何确保它是正确的 href 而不仅仅是第一个?
PHP:这部分工作正常。
while ($row = $q->fetch()):
?>
<li class="item <?php echo $row['type'];?>"><a href="<?php echo $row['link'];?>" class="test-popup-link">
<?php if($row['img']) { ?>
<img src="upload/videoCovers/<?php echo $row['img'];?>" alt="<?php echo $row['title'];?>">
<?php }
else { ?>
<img src="upload/videoCovers/playBtn.png" alt="<?php echo $row['title'];?>">
<?php } ?>
</a>
</li>
JavaScript:
$(document).ready(function(){
var videoLink = $(".test-popup-link").attr("href");
$('.test-popup-link').magnificPopup({
items: {
src: videoLink
},
type: 'iframe' // this is default type
});
});
我对
那个插件一无所知,但是,您可能希望使用 .test-popup-link
类遍历所有元素并调用.magnificPopup()
。请考虑以下事项:
$(document).ready(function(){
$('.test-popup-link').each(function() {
$(this).magnificPopup({
items: {
src: $(this).attr('href')
},
type: 'iframe' // this is default type
});
});
});
编辑:快速浏览Magnific Popup文档后,看起来您也可以使用以下示例。
[...]如果要从一个容器中的元素列表创建弹出窗口,请使用此方法。请注意,此方法不启用库模式,它只是减少了单击事件处理程序的数量;每个项目将作为单个弹出窗口打开
.html
<div class="parent-container">
<a href="path-to-image-1.jpg">Open popup 1</a>
<a href="path-to-image-2.jpg">Open popup 2</a>
<a href="path-to-image-3.jpg">Open popup 3</a>
</div>
JavaScript
$('.parent-container').magnificPopup({
delegate: 'a', // child items selector, by clicking on it popup will open
type: 'image'
// other options
});
因此,在您的情况下,您可能需要考虑将ul
父级定位到您的列表中。
让我指出您的代码中的几个问题
$(document).ready(function(){
var videoLink = $(".test-popup-link").attr("href"); // ( 1 )
$('.test-popup-link').magnificPopup({ //( 2 )
items: {
src: videoLink //( 3 )
},
type: 'iframe' // this is default type
});
});
-
$(".test-popup-link").attr("href");
在这里,代码$(".test-popup-link")
将返回带有类test-popup-link
的所有元素,因此您将获得节点集合,这很好。现在,当您执行.attr("href")
时,仅选择集合中的第一个节点并返回其 href。 - 您正在尝试将插件应用于具有类
test-popup-link
的所有元素,除非插件的内部配置相同,否则这很好。在您的情况下,它的videoLink
值会有所不同,因此您不能以通用方式使用它。您必须使用循环来应用插件。 - 如上所述,您的
videoLink
仅包含第一个元素 href,并且只有第一个 href 值将应用于所有元素。
因此,解决方案是使用循环来应用插件。这是代码
$(document).ready(function(){
$.each('.test-popup-link',function() { //looping
$(this).magnificPopup({ // apply to each element in the loop
items: {
src: $(this).attr('href') // apply its respective href
},
type: 'iframe' // this is default type
});
});
});
$('.load-video').on('click', function(e) {
e.preventDefault();
var link = $(this).attr('href');
$('.test-popup-link').magnificPopup({
items: {
src: link
},
type: 'iframe' // this is default type
});
});
在标记中添加类
<a class="load-video test-popup-link" href="<?php echo $row['link'];?>">