You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

点击DIV加载iFrame实现懒加载 如何通过循环避免重复写JS代码

优化实现方案

方案1(更易维护,推荐):用自定义属性实现无需循环的通用逻辑

不需要为每个元素设置带数字后缀的id,只需新增自定义属性存储对应视频地址,后续新增视频无需修改JS代码,30个视频都可以复用同一段逻辑。

调整后HTML结构

<!-- 每个视频模块都按这个结构编写,仅需修改封面图地址和data-video-src属性值即可 -->
<div class="embed-responsive embed-responsive-16by9 iframe-holder">
  <div class="playButtonContainer" style="height:300px;width:100%;padding-top: 24%;background-image:url(https://i.insider.com/5c79a8cfeb3ce837863155f5?width=700&format=jpeg&auto=webp);background-repeat: no-repeat;">
    <div class="playButton" data-video-src="https://www.youtube.com/embed/kujV1qHr1ow">Play Video</div>
  </div>
</div>

<div class="embed-responsive embed-responsive-16by9 iframe-holder">
  <div class="playButtonContainer" style="height:300px;width:100%;padding-top: 24%;background-image:url(https://i.insider.com/5ea6fd9dd553f808ba5bf897?width=700&format=jpeg&auto=webp);background-repeat: no-repeat;">
    <div class="playButton" data-video-src="https://www.youtube.com/embed/WDlu1OhvYBM">Play Video</div>
  </div>
</div>

对应的JS代码

同时修复原有逻辑中「点击一个视频后其余视频无法加载」的bug:

$(function(){
    // 一次性绑定所有播放按钮的点击事件
    $('.playButton').click(function(){ 
        // 读取当前点击按钮对应的视频地址
        const videoSrc = $(this).data('video-src');
        // 定位到当前视频对应的外层容器
        const holder = $(this).closest('.iframe-holder');
        // 仅判断当前容器是否已加载iframe,不影响其他视频
        if(!holder.find('iframe').length) {
            holder.html(`<iframe class="embed-responsive-item" style="height:300px; width:100%" src="${videoSrc}" allowfullscreen></iframe>`);
        }
    });   
});

方案2:基于原有HTML结构的循环实现

如果你不想调整现有HTML结构,可以通过遍历序号+预存视频地址数组的方式实现:

$(function(){
    // 按序号顺序填入30个视频的iframe地址
    const videoList = [
        'https://www.youtube.com/embed/kujV1qHr1ow',
        'https://www.youtube.com/embed/WDlu1OhvYBM'
        // 剩余28个地址按顺序补充到这里即可
    ];
    // 循环绑定1-30号视频的点击事件
    for(let i = 1; i <= 30; i++) {
        $(`#playButton${i}`).click(function(){ 
            if(!$(`#iframeHolder${i} iframe`).length) {
                $(`#iframeHolder${i}`).html(`<iframe class="embed-responsive-item" style="height:300px; width:100%" src="${videoList[i-1]}" allowfullscreen></iframe>`);
            }
        }); 
    }
});

内容的提问来源于stack exchange,提问作者JamesReed68

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 14:36:05