javascript - 如何选择 while 循环中的 href 变量?

标签 javascript php href attr

我有一个从数据库中选择多个图像的 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 Documentation 后,看起来您也可以使用以下示例。

[...] Use this method if you are creating a popup from a list of elements in one container. Note that this method does not enable gallery mode, it just reduces the number of click event handlers; each item will be opened as a single 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 父级定位到您的列表中。

关于javascript - 如何选择 while 循环中的 href 变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36050360/

相关文章:

php - 有什么方法可以将值从 JavaScript 发送到 CodeIgniter 中的 Controller 吗?

javascript - 未捕获的语法错误 : x is not defined

javascript - 如何将数字验证更改为字符串验证

php - 迁移wordpress服务器并使用旧数据库

php - 我的工厂应该创建所有对象实例吗?包括新实体吗?

asp.net-mvc - 属性有一个空格,而 Href 会忽略其后的所有内容

javascript - 单击事件到自动事件图像在 Jquery 中更改

javascript - 我使用哪个Youtube API搜索视频?

javascript - d3 添加 html 链接到表中的数据列

html - 我的 <a href 没有将我发送到文档中的元素