2012-04-24 38 views
1

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

可能重複[什麼是通過一組在JavaScript元素的循環最好的方法是什麼?(HTTP://計算器.COM /問題/ 157260 /什麼最最好的方式對環通-A-設置元素合的JavaScript) – 2012-04-24 18:22:43

回答

1
window.onload = function() { 
    var elements = document.getElementsByTagName('div'); 
    for (var i = 0; i < elements.length; i++) { 
    append_iframe(elements[i]); 
    } 
} 

function append_iframe(div) { 
    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); 
    div.appendChild(iframe); 
} 
+0

仍然只加載最後一個div用一個iframe – Patriotec 2012-04-24 20:03:01

+0

您的代碼很接近。我只是不得不擺弄它,所以無論我在頁面中使用了多少次,它都會加載。 Thanx – Patriotec 2012-04-24 21:35:06

+0

很高興我幫助過,如果你願意,你可以編輯我的答案和工作例子,這可以幫助未來的用戶有同樣的問題。 – 2012-04-24 23:10:10

0

不是一個jQuery的傢伙,但我想這樣的作品的

$("div").each(function(d) { 
    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); 
    this.appendChild(iframe); 
}); 
相關問題