如何在JavaScript中更改iframe的源位置?你如何在JavaScript中更改iframe的源位置?
例如,而是一個按鈕或鏈接的點擊,改變這種:
<iframe src=""></iframe>
...到這一點:如果你想要做一個更好的
<iframe src="http://stackoverflow.com/"></iframe>
而且,如何更改同一頁面中的多個iframe(使用name
或其他標識符)?
如何在JavaScript中更改iframe的源位置?你如何在JavaScript中更改iframe的源位置?
例如,而是一個按鈕或鏈接的點擊,改變這種:
<iframe src=""></iframe>
...到這一點:如果你想要做一個更好的
<iframe src="http://stackoverflow.com/"></iframe>
而且,如何更改同一頁面中的多個iframe(使用name
或其他標識符)?
首先,爲你指定一個id。這看起來像
<iframe id="youridname" src=""></iframe>;.
然後你的JavaScript命令將
document.getElementById("youridname").src = "http://stackoverflow.com";
非常感謝。我假設你首先回答,因此我接受你的答案。他們都表現出「9個小時前回答」,所以我選擇了最好的那個,這是你的。 – Xonatron
這與修改任何其他標籤沒有區別。獲取元素並設置屬性:
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。)
document.getElementById("test").setAttribute("src", "http://stackoverflow.com");
你可以在一個頁面從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;
這將無法正常工作,堆棧溢出使用幀破壞,不能被陷害(至少不容易):-) ..... – adeneo