頁面裡並排兩個 iframe,想讓左邊的值同步到右邊,該怎麼做?核心觀念是:iframe 內部的視窗仍然掛在父頁面的 frames 集合裡,因此可以透過 parent.frames 找到兄弟框架,再直接操作對方的 document。
用表格把兩個 iframe 上下排好,並各自取名字 aa 與 bb——這兩個 name 就是後續跨框架存取的關鍵。
<body>
<table border="1" width="100%">
<tr>
<td width="100%"><iframe src="iframe1.htm" name="aa"></iframe></td>
</tr>
<tr>
<td width="100%"><iframe src="iframe2.htm" name="bb"></iframe></td>
</tr>
</table>
</body>
按下按鈕時,透過 parent.frames["bb"] 取得右邊框架的視窗物件,再往它的 document 裡寫值。
<html>
<title>1</title>
<head>
<script type="text/JavaScript">
function aa() {
parent.frames["bb"].document.all["TextBox3"].value = document.getElementById("TextBox1").value;
parent.frames["bb"].document.all["TextBox4"].value = document.getElementById("TextBox2").value;
alert(parent.frames["bb"].document.all["TextBox3"].value);
alert(parent.frames["bb"].document.all["TextBox4"].value);
}
</script>
</head>
<body>
<form id="a">
<input id="TextBox1" type="text" value="1"/>
<input id="TextBox2" type="text" value="2"/>
<input id="T" type="button" value="傳值給右邊" onclick="aa();"/>
</form>
</body>
</html>
接收端什麼都不用做,只要把 id 準備好即可。
<html> <title>2</title> <head></head> <body> <form id="b"> <input id="TextBox3" type="text" value="1231111"/> <input id="TextBox4" type="text" value="123"/> </form> </body> </html>
範例中用的 document.all 是 IE 時代的寫法,現代的等效做法是用 contentWindow.document.getElementById(),或直接 parent.frames["bb"].document.getElementById("TextBox3")。
其次,跨 iframe 存取有同源政策限制:兩個框架必須同來源(同 protocol、同 host、同 port),否則瀏覽器會直接拋錯。若 iframe 載入的是外部網域,就只能改用 postMessage 溝通。
最後,若要在 iframe 中存取其父頁面,寫 window.parent 即可;但要小心巢狀多層時 parent 與 top 的差別。