2015-05-09 87 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

相关问题