如何指定不同的按钮来加载iframe中的其他网址?

时间:2015-05-09 00:46:20

标签: javascript jquery html button iframe

我遇到了iFrames的问题。

我有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 =&#34; loadiframe&#34;由于按钮分散在整个页面上,我无法将按钮放在一起并只调用一次。

有关解决此问题或解决方法的任何建议吗?

2 个答案:

答案 0 :(得分:4)

您可以在按钮上使用内联点击事件:

//select[@id='pa_size']/option[@class='active']/@value

您也可以使用<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"

不需要JavaScript。

答案 1 :(得分: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'));
})