如我們建立表單FatherPage.htm:
XML-Code:
複製代碼 代碼如下:<script type="text/javascript">
function OpenChildWindow()
{
window.open('ChildPage.htm');
}
</script>
<input type="text" id="txtInput" />
<input type="button" value="OpenChild" onclick="OpenChildWindow()" />
然後在ChildPage.htm中即可通過window.opener來訪問父表單中的元素:
XML-Code: 複製代碼 代碼如下:<script type="text/javascript">
function SetValue()
{
window.opener.document.getElementById('txtInput').value
=document.getElementById('txtInput').value;
window.close();
}
</script>
<input type="text" id="txtInput" />
<input type="button" value="SetFather" onclick="SetValue()" />
其實在開啟子表單的同時,我們也可以對子表單的元素進行賦值,因為window.open函數同樣會返回一個子表單的引用,因此FatherPage.htm可以修改為:
XML-Code: 複製代碼 代碼如下:<script type="text/javascript">
function OpenChildWindow()
{
var child = window.open('ChildPage.htm');
child.document.getElementById('txtInput').value
=document.getElementById('txtInput').value;
}
</script>
<input type="text" id="txtInput" />
<input type="button" value="OpenChild" onclick="OpenChildWindow()" />
通過判斷子表單的引用是否為空白,我們還可以控制使其只能開啟一個子表單:
XML-Code: 複製代碼 代碼如下:<script type="text/javascript">
var child
function OpenChildWindow()
{
if(!child)
child = window.open('ChildPage.htm');
child.document.getElementById('txtInput').value
=document.getElementById('txtInput').value;
}
</script>
<input type="text" id="txtInput" />
<input type="button" value="OpenChild" onclick="OpenChildWindow()" />
光這樣還不夠,當關閉子表單時還必須對父表單的child變數進行清空,否則開啟子表單後再關閉就無法再重新開啟了:
XML-Code: 複製代碼 代碼如下:<body onunload="Unload()">
<script type="text/javascript">
function SetValue()
{
window.opener.document.getElementById('txtInput').value
=document.getElementById('txtInput').value;
window.close();
}
function Unload()
{
window.opener.child=null;
}
</script>
<input type="text" id="txtInput" />
<input type="button" value="SetFather" onclick="SetValue()" />
</body>