2012-04-24 30 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); 
}); 
相关问题