javascript - 依次渲染多个 iframe

标签 javascript html jquery css iframe

我有一个 url 数组,我想用它们在页面上渲染 iframe。我的目标是在显示下一个 iframe 之前显示 iframe 的内容,该过程一直持续到我为数组中的所有 url 渲染 iframe 为止。不确定我做错了什么,下面是我编写的用于处理此问题的脚本。对于单个 url 效果很好,但是对于多个 url,它会尝试在页面上渲染任何 iframe 之前从所有 url 中获取所有内容。

<script>
    get('endpoint to fetch the urls').then(data => { // makes api request to fetch the urls.
        const lti_launch_urls = data['lti_launch_urls'] 
        lti_launch_urls.forEach((launch_url, index) => {


                const iframe = document.createElement('iframe')
                iframe.sandbox = "allow-same-origin allow-scripts allow-popups allow-forms"
                iframe.width = "100%"
                iframe.frameBorder = "0"
                iframeId = "iframe-" + index
                iframe.id = iframeId
                iframe.src = launch_url
                document.body.appendChild(iframe)
                iframe.contentWindow.postMessage(style, "*");
        })

    })
</script>

最佳答案

我会建议类似以下的内容。将您的逻辑放入可重用的方法中,该方法执行采用索引的 iframe 生成。从索引 0 开始调用它以显示第一个 iframe。然后,一旦 iframe 遇到加载事件,就使用下一个索引再次调用该方法来执行逻辑迭代。

    const lti_launch_urls = data['lti_launch_urls'];
    const loadNextIframe = index => {
      if (index >= lti_launch_urls.length) return;

      const launch_url = lti_launch_urls[index];
      const iframe = document.createElement('iframe');

      iframe.sandbox = "allow-same-origin allow-scripts allow-popups allow-forms";
      iframe.width = "100%";
      iframe.frameBorder = "0";
      iframeId = "iframe-" + index;
      iframe.id = iframeId;
      iframe.src = launch_url;

      iframe.addEventListener('load', () => loadNextIframe(++index));

      document.body.appendChild(iframe);
      iframe.contentWindow.postMessage(style, "*");
    };

    loadNextIframe(0);

关于javascript - 依次渲染多个 iframe,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61545996/

相关文章:

javascript - CSS3 : nested menu in full screen overlay

css - 内容在 ie6 中被下推

jquery - 使用 jQuery 动态添加自定义 HTML 表单文件输入

jquery - 有谁知道如何模拟 www.foodnetwork.com 上的搜索框?

javascript - 从 1 个 HTML 输入获取多个 JavaScript 变量

javascript - 为什么 .innerText 在 Firefox 中不起作用?

javascript - Ember 中的下拉列表;

javascript - Javascript 中的不同作用域 - 词法与动态

javascript - 使用 Handlebars 渲染对象的嵌套数组

javascript - 访问自定义验证规则中的其他字段