0

While rendering iframes, I use the code:

ifrm = document.createElement("IFRAME");
ifrm.style.width = "100%";
ifrm.style.height = 600+"px";
function makeFrame() {
document.body.appendChild(ifrm);
}

However, this keeps appending iframes below the existing one, each time I call the function makeFrame(). So, if I call makeFrame() (say thrice), then I get three iframes one below the previous. How to prevent this and replace the existing one instead of appending to the last one?

4

3 回答 3

0

Create a div . Let's say div id is iframecontainer so your code should be like:

<div id="iframecontainer">
<!-- Iframe goes here -->

</div>

Now simply getElementById with javascript and set the innerHTML to "" before appending the iframe.

于 2013-01-11T14:54:16.430 回答
0

The simplest answer:

If you want to change your code as little as possible, and you're certain that you'll only have exactly one iframe on the page at any given time

function makeFrame() {
oldiframe = document.getElementsByTagName("IFRAME")[0] 
// getElementsByTagName will return an array (a list). 
// Adding [0] will return the first (and, under our assumptions, only) element
ifrm = document.createElement("IFRAME");
ifrm.style.width = "100%";
ifrm.style.height = 600+"px";
document.body.replaceChild(ifrm, oldiframe);
}
于 2013-01-11T15:02:09.133 回答
0

Hi @mikemxm I was finally able to solve the problem. The final code looks like this:

oldiframe = document.getElementsByTagName("IFRAME")[0]; 
ifrm = document.createElement("IFRAME");
ifrm.style.width = "100%";
ifrm.style.height = 600+"px";
function makeFrame() {
   if(oldiframe == null)
     document.body.appendChild(ifrm);
   else
     document.body.replaceChild(ifrm, oldiframe);
}

And thanks for the warning against iframes. Do you know of any better way/technology to render content from external websites? Can there be any copyright issues? Thanks.

于 2013-01-12T05:24:07.193 回答