如何分配不同的按钮以在 iframe 中加载不同的 URL?

How can I assign different buttons to load a different URL in an iframe?

我被 iFrame 的问题困住了。

我有 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="loadiframe",因为按钮散布在整个页面上,我无法真正将按钮放在一起并只调用它 1 次。

关于解决此问题或解决此问题的任何建议?

请更改此

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

至此

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

querySelector : Returns the first element within the document (using depth-first pre-order traversal of the document's nodes) that matches the specified group of selectors.

querySelectorAll: Returns a list of the elements within the document (using depth-first pre-order traversal of the document's nodes) that match the specified group of selectors.

而且,这是我的 jquery 解决方案:

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

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

<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。