2012-04-24 78 views
12

我想加载/附加iframe到与常规JavaScript的div。我可以用JQuery做到这一点,但没有问题,但我不想包含js文件。我不断收到错误'document.getElementById(“ad54”)'(或任何我分配div的ID)。我有以下代码:使用javascript附加到div创建iframe

var link = "http://www.google.com" 
var iframe = document.createElement('iframe'); 
iframe.frameBorder=0; 
iframe.width="300px"; 
iframe.height="250px"; 
iframe.id="randomid"; 
iframe.setAttribute("src", link); 
document.getElementById("ad54").appendChild(iframe); 

<div id="ad54"></div> 

回答

28

你应该写这里面的window.onload像

window.onload = function(){ 
    var link = "http://www.quirksmode.org/iframetest2.html" 
var iframe = document.createElement('iframe'); 
iframe.frameBorder=0; 
iframe.width="300px"; 
iframe.height="250px"; 
iframe.id="randomid"; 
iframe.setAttribute("src", link); 
document.getElementById("ad54").appendChild(iframe); 

} 
+0

不会产生一个IFRAME。虽然,我不再接收萤火虫 – Patriotec 2012-04-24 16:43:24

+7

下的任何错误,Google.com将不会在iframe中加载。尝试其他链接。见https://developer.mozilla.org/zh/The_X-FRAME-OPTIONS_response_header – Sethunath 2012-04-24 16:45:28

+0

你是对的。我尝试了另一个网站,它的工作。感谢您的帮助 – Patriotec 2012-04-24 16:51:16