概念
當您打開主頁的窗口,不斷向打開的窗口中的引用(將其推到一個數組工作得很好)。當點擊主頁面按鈕時,關閉每個引用的窗口。
客戶端腳本
這種JavaScript的主頁。這適用於HTML或ASPX頁面。
var arrWindowRefs = [];
//... assume many references are added to this array - as each window is open...
//Close them all by calling this function.
function CloseSpawnedWindows() {
for (var idx in arrWindowRefs)
arrWindowRefs[idx].close();
}
打開一個窗口,將其推到上述陣列看起來像這樣:
// Spawn a child window and keep its reference.
var handle = window.open('about:blank');
arrWindowRefs.push(handle);
Microsoft's JavaScript window.open(..) method and its arguments are outlined here。
不同的瀏覽器可能會有變化或專有的方式來保持對打開的窗口的引用或枚舉,但這種純JavaScript方式與瀏覽器非常兼容。
按鈕
最後HTML輸入按鈕發起上面的代碼將
<input type="button"
name="btn1" id="btn1" value="Click Me To Close All Windows"
onclick="CloseSpawnedWindows()">
如果它是一個ASP.NET按鈕控制然後調用JavaScript這樣
<asp:Button ID="Button1" runat="server" Text="Click Me To Close All Windows"
OnClientClick="CloseSpawnedWindows()" />
疑難解答ASP.NET客戶端腳本(回傳和AJAX修復)
如果你的aspx頁面回發到服務器,客戶端代碼將被破壞,失去它的陣列子窗口引用(和這些窗口將保持開放)。如果這是一個問題,您可能需要使用AJAX進行部分頁面刷新,以防止整個頁面及其腳本被破壞。
對於ASP.NET AJAX你會使用的東西就像一個ScriptManager實例enable partial page refresh內UpdatePanel controls (lots of samples)(使用Framework 3.5的樣品圖所示)。
<%@Page... %>
<asp:ScriptManager EnablePartialRendering="True" /> Enable AJAX.
<script>
// PUT JAVASCRIPT OUT HERE SOMEWHERE.
// Notice the client script here is outside the UpdatePanel controls,
// to prevent script from being destroyed by AJAX panel refresh.
</script>
<asp:UpdatePanel ID="area1" runat="server" ... > ... </asp:UpdatePanel>
<asp:UpdatePanel ID="area2" runat="server" ... > ... </asp:UpdatePanel>
etc...
有關ASP.NET AJAX的更多詳細信息可以提供,但這只是一個開始,以防您需要它。
請記住,在AJAX的情況下,不刷新包含上述客戶端腳本的網頁的一部分,因爲你想讓它堅持通過服務器回調數組。