2015-05-09 84 views
0

我被困在iFrames的問題上。如何分配不同的按鈕來在iframe中加載不同的URL?

我有6個按鈕,我想在按下時打開不同的URL。

的按鈕HTML代碼:

<div class="loadiframe"> 
    <button id="b1" data-src="http://Site1.com/">Button 1</button> 
</div> 
<div class="loadiframe"> 
    <button id="b2" data-src="http://Site2.com">Button 2</button> 
</div> 

等..

的iFrame的HTML代碼:

<iframe id='frame' frameborder="0" scrolling="no"> 

和JavaScript:

function iframeChange() { 
    var buttons = document.querySelector(".loadiframe"), 
     iframe = document.getElementById('frame'); 

    buttons.addEventListener("click", function (e) { 
     iframe.src = e.target.dataset.src; 
    }); 
} 
window.onload = iframeChange; 

我最大問題將會是class =「lo adiframe「,因爲這些按鈕分散在整個頁面中,我無法真正將這些按鈕放在一起並只調用一次。

任何建議,以解決這個問題或解決方法嗎?

+0

很抱歉忘記在​​上添加結束標籤,但問題不在於此。 – KillahHerb

回答

3

您可以在按鈕上使用內聯單擊事件:

<iframe name="frame" id="frame" src="http://site1.com"></iframe> 

<button type="button" onClick="document.getElementById('frame').src='http://site2.com'">Button #1</button> 
<button type="button" onClick="document.getElementById('frame').src='http://site3.com'">Button #2</button> 
<button type="button" onClick="document.getElementById('frame').src='http://site4.com'">Button #3</button> 

你也可以使用一個<a>代替<button>,然後將target="frame"添加到您的錨點:

<iframe name="frame" src="http://site1.com"></iframe> 

<a href="http://site2.com" target="frame">Link 1</a> 
<a href="http://site3.com" target="frame">Link 2</a> 
<a href="http://site4.com" target="frame">Link 3</a> 

不需要JavaScript。

+0

感謝過於認爲它超過我應該 – KillahHerb

1

請把這個

var buttons = document.querySelector(".loadiframe"), 

這個

var buttons = document.querySelectorAll(".loadiframe button"), 

querySelector:返回文檔中的第一個元素(使用文檔的節點 深度優先前序遍歷),其匹配 指定的一組選擇器。

querySelectorAll:返回與指定的選擇器組匹配的文檔中的元素列表(使用深度優先遍歷文檔節點)。

而且,這裏是我的jQuery的解決方案:

$('.loadiframe >button').click(function(){ 
    $('#frame').attr('src', $(this).data('src')); 
}) 
+0

還沒有加載。與var buttons = document.querySelector(「。loadiframe」),它加載第一個按鈕,但所有添加它不加載。我嘗試過之前和即時通訊x( – KillahHerb

+0

@KillahHerb你試過jquery – renakre

+0

我想避免使用jquery,但是謝謝@zep_fan找到了我的方式 – KillahHerb

相關問題