3

如何在 JavaScript 中更改 iframe 的源位置?

例如,但是点击一个按钮或一个链接,改变这个:

<iframe src=""></iframe>

...进入这个:

<iframe src="http://stackoverflow.com/"></iframe>

而且,如果您想做得更好,如何更改同一页面中的多个 iframe(使用name或其他标识符)?

4

4 回答 4

3

首先,为您的 iframe 分配一个 id。这看起来像

<iframe id="youridname" src=""></iframe>;. 

那么您的 JavaScript 命令将是

document.getElementById("youridname").src = "http://stackoverflow.com";
于 2012-12-14T05:23:56.060 回答
2

这与修改任何其他标签没有什么不同。获取元素,并设置属性:

document.getElementsByTagName("iframe")[0].src = "http://stackoverflow.com";

您可以选择您喜欢的任何属性。例如,如果您有<iframe data-id='some-frame' src='http://stackoverflow.com'></iframe>,那么您可以针对任一属性进行选择:

var soFrames = document.querySelectorAll("iframe[src*='overflow']");
if (soFrames.length > 0) {
    soFrames[0].src = "something.com";
}

或者:

var soFrames = document.querySelectorAll("iframe[data-id='some-frame']")

(请注意,存在安全限制,因此您不能只在页面的 iframe 中显示任何随机网站,例如 Stackoverflow.com。)

于 2012-12-14T05:23:17.730 回答
2

您可以从 引用页面中的框架window.frames。这包含框架window对象的集合。从那里你修改location.href框架的window

frames[0].location.href = "page1.htm";
frames[1].location.href = "page2.htm";

您还可以通过引用框架元素的contentWindow属性来访问框架的窗口:

document.getElementById("frame1").contentWindow.location.href = "page1.htm";

要倒退,即从它的窗口中获取框架元素frameElement,请使用以下属性:

frames[0].frameElement;
于 2012-12-14T05:38:55.233 回答
1
document.getElementById("test").setAttribute("src", "http://stackoverflow.com");
于 2012-12-14T05:27:39.373 回答