簡體   English   中英

我如何將內容動態加載到 iframe

[英]how do i dynamically load content into an iframe

我有一些代碼應該動態加載 iframe。 問題是我有一個 function 應該使其級聯到附加到 iframe 的下一個 id。 我需要有人幫助用我的代碼確定問題。

 const $iframe = $("#content-frame"); $($iframe).attr('src', cath); var cath = 'https://exanple.com' + myIds[i] + '/embed/dynamic?'; console.log(cath); const myIds = ['1_aq4jiqb', '1_4u0ocu4u']; function switchId() { for (let i = 0; i < myIds.length; i++) { cath = 'https://www.exanple.com' + myIds[i] + '/embed/dynamic?'; } } setInterval(function() { switchId() }, 3000);
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <iframe id="content-frame" src="" width="400px" height="400px"></iframe>

這會一遍又一遍地覆蓋cath cath = 'https://www.exanple.com' + myIds[i] + '/embed/dynamic?'; 而且您沒有在任何地方使用cath。

除了使用 setInterval 獲得的循環之外,您不想要任何其他循環

也無需將 jQuery object 轉換為 jQuery object。

我把清單包裝起來

 const $iframe = $("#content-frame"); const myIds = ['1_aq4jiqb', '1_4u0ocu4u']; let cnt = 0; setInterval(function() { const url = 'https://www.example.com/' + myIds[cnt] + '/embed/dynamic?'; $iframe.attr('src', url); console.log(url); cnt++; if (cnt >= myIds.length) cnt = 0; // wrap the list }, 3000);
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <iframe id="content-frame" src="" width="400px" height="400px"></iframe>

只需更改 iframe 元件SRC即可解決此問題。

    const myIds = ['1_aq4jiqb', '1_4u0ocu4u'];
    let cnt = 0;
    setInterval(function() {
       const src = 'https://www.example.com/' + myIds[cnt] + '/embed/dynamic?';
       document.getElementById('myIframe').src = src;
       cnt++;
       if (cnt >= myIds.length) cnt = 0; 
    }, 3000);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM