【问题标题】:Dynamically set the src of an iframe to delay loading动态设置 iframe 的 src 以延迟加载
【发布时间】:2020-08-13 17:21:56
【问题描述】:

我有一个包含多个链接和多个 iframe 的页面。我设法让 iframe 正常隐藏,然后在单击相应链接时变得可见。

但是,由于 iframe 有很多,我希望它们仅在它们可见时才加载。目前它们都在页面第一次加载时加载,这使得它有点慢。

我试图填充 iframe 的 src 仅当它的链接被点击时,但我似乎无法管理它。我要么没有加载它们,要么每次单击任何链接时都加载它们。

<ul>
  <li> <a href="#index1" class="index-topic">Topic Name</a> </li>
  <li> <a href="#index2" class="index-topic">Topic Name</a> </li>
  <li> <a href="#index3" class="index-topic">Topic Name</a> </li>
</ul>

<section id="index1" class="index-content">
  <div>
    Some text about the topic
  </div>
  <div>
    <iframe class="data-embed" data-src="data-source-URL" src=""></iframe>
  </div>
</section>
$('.index-topic').click(function(e) {
  //Prevent scrolling of page on click
  event.preventDefault();

  //This is the section that isn't working:
  $(this).find('iframe').attr("src", function() {
    return $(this).data("src");
  });

  //Toggle target tab
  $($(this).attr('href')).addClass('active').siblings().removeClass('active');
});

【问题讨论】:

  • 您正试图在点击的&lt;a&gt; 中“找到”iframe。尝试使用您添加 active 类的元素;)

标签: jquery iframe


【解决方案1】:

问题是因为您在this 上使用find(),它指的是被点击的a,而iframe 不是该元素的后代。

要解决此问题,您可以使用单击的ahref 属性作为选择器。

$('.index-topic').click(function(e) {
  e.preventDefault();

  let selector = $(this).attr('href');
  $(selector).find('iframe').prop("src", function() {
    return $(this).data("src");
  }).addClass('active').siblings().removeClass('active');
});
<ul>
  <li> <a href="#index1" class="index-topic">Topic Name</a> </li>
  <li> <a href="#index2" class="index-topic">Topic Name</a> </li>
  <li> <a href="#index3" class="index-topic">Topic Name</a> </li>
</ul>

<section id="index1" class="index-content">
  <div>
    Some text about the topic
  </div>
  <div>
    <iframe class="data-embed" data-src="data-source-URL" src=""></iframe>
  </div>
</section>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-18
    • 2015-01-31
    • 1970-01-01
    相关资源
    最近更新 更多