gpt4 book ai didi

jquery - 动态设置iframe的src以延迟加载

转载 作者:行者123 更新时间:2023-12-01 05:11:38 26 4
gpt4 key购买 nike

我有一个包含多个链接和多个 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');
});

最佳答案

问题是因为您在 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>

关于jquery - 动态设置iframe的src以延迟加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61504884/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com