我忘了在最后一个问题中包含'在多个页面上运行多次':Create iframe with javascript appending to a div需要JavaScript代码在一个页面中运行多次。对于每个div
我需要在同一页面上的多个div上运行代码。现在下面的代码只在最后一个div上运行一次。例如,如果我有3个div,所有3个应该有一个iframe附加到它。正常的JavaScript。尝试不使用JQuery。
window.onload = function(){
var link = "http://www.somesite.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); //<--this id will be dynamically generated to match div's
}
<div class="ad" id="1"></div>
<div class="ad" id="2"></div>
<div class="ad" id="3"></div>
编辑:在IE9,Chrome,Safari浏览器,Firefox和歌剧测试。此代码有效。不需要JQuery或循环。此代码将在您使用它的任何地方创建iframe。
var link = "http://www.somesite.com"
document.write(iframe);
var myIframe = parent.document.getElementById("randomid");
myIframe.height = 250;
myIframe.width = 300;
myIframe.src = link;
myIframe.style.border = "0px";
myIframe.style.padding = "0px";
可能重复[什么是通过一组在JavaScript元素的循环最好的方法是什么?(HTTP://计算器.COM /问题/ 157260 /什么最最好的方式对环通-A-设置元素合的JavaScript) – 2012-04-24 18:22:43