我被 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 次。
关于解决这个问题或解决它的方法有什么建议吗?
最佳答案
您可以在按钮上使用内联点击事件:
<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"
给你的 anchor :
<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。
关于javascript - 如何分配不同的按钮以在 iframe 中加载不同的 URL?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30134801/