2012-04-24 4 views
1

私はここにある最後の質問に「一度に複数回実行」することを忘れました:Create iframe with javascript appending to a div1ページで複数回実行するにはjavascriptコードが必要です。各部門毎

同じページ内の複数のdivにコードを実行する必要があります。今のところ、以下のコードは最後のdivで1回しか実行されません。たとえば、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、およびOperaでテスト済みです。このコードは機能します。 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

可能重複うまくいくと思う:// stackoverflowのを.com/questions/157260/whats-the-best-way-to-elements-of-elements-in-javascript) –

答えて

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

+0

コードが閉じています。私はちょうどそれを試す必要があったので、何ページに何回使用してもロードされてしまいました。 Thanx – Patriotec

+0

私は助けてくれてありがたいことですが、もしあなたが望むのであれば、同じ問題を抱えている将来のユーザーに役立つでしょう。 –

0

ないjQueryの男が、私は、これは[JavaScriptで要素のセットをループするための最良の方法は何ですか?](HTTPの

$("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); 
}); 
関連する問題