我忘了在最後一個問題中包含'在多個頁面上運行多次':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