简体   繁体   中英

Dynamically created iFrame is null when called from a page loaded by JQuery

I have a dynamically created iframe made with regular javascript. It works great when its called from a static page by regular means, but when called from a page loaded by Jquery, I get a 'myIframe is null' error.

var link = 'http://www.blah.com'
var iframe='<iframe class="adframe" id="randomnumberhere" name="widget" src="#" width="300" height="250" marginheight="0" marginwidth="0" frameborder="no" scrolling="no"></iframe>';

document.write(iframe);
var myIframe=parent.document.getElementById("randomnumberhere");
myIframe.height=250;
myIframe.width=300;
myIframe.src=link;
myIframe.style.border="0px";
myIframe.style.padding="0px";

I solved this one by adding a div with a unique id then append the iFrame to that div. It seems document.write can make the object, but appending to that element wasn't happening. The working code is below.

Have a dynamically created random number for the div in the html already there:

<div id="randomid"></div>

Then I made a function to append to that div with that specific id

function makeFrame(){
var link = 'http://blah.com'
ifrm = document.createElement("IFRAME");
ifrm.setAttribute("src", link);
ifrm.style.width="300px";
ifrm.style.height="250px";
ifrm.style.border="0px";
ifrm.style.padding="0px";
document.getElementById('randomid').appendChild(ifrm);
}
makeFrame();

This will only work if the div is already on the page. I couldn't figure out a way to dynamically make the div and then append the iFrame to that div. Document.write made the div, but it couldn't append the iFrame to that element. Perhaps a delay would make it work? Below is what I tried, but didn't work.

var iDiv='<div id="randomid"></div>';
document.write(iDiv);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM