Javascript 兩個表單之間傳值實現代碼

來源:互聯網
上載者:User

如我們建立表單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>

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.