如何在窗口关闭时更新全局变量

How to update global variable when window closes?

本文关键字:更新 全局变量 窗口      更新时间:2023-09-26

第一次来。我正在尝试用Javascript编写一些具有这些功能的代码。

首先,如果一个链接被点击,并且没有现有的弹出窗口,将创建一个弹出窗口,导航到该链接。

然而,如果第二个链接被点击,并且有一个现有的弹出窗口,它将运行一些AJAX函数。我们不会导航到那个链接。

但是,如果点击了另一个链接,并且弹出窗口已经关闭,它将再次打开窗口(并导航到该链接)

我能想到的唯一方法,让我解决这个问题是使用一个全局变量,但它不工作。有人能帮忙吗?谢谢!

这是我的文件

HTML

<a href="javascript:;" onclick="javascript:displayWindow=openwindowPreview(1, displayWindow); return false">1</a>
<br/>
<a href="javascript:;" onclick="javascript:displayWindow=openwindowPreview(4, displayWindow); return false">4</a>
Javascript

var displayWindow = null;
var test = 'test';
function openwindowPreview(id, winObject) {
    // check if the window already exists
    if (winObject != null) {
        // the window has already been created, but did the user close it?
        // if so, then reopen it. Otherwise make it the active window.
        if (!winObject.closed) {
            winObject.focus();
            return winObject;
        }
    }
    if (test != 'test') {
        if (winObject.closed) {
            test = 'test';
        } else {
            alert('ajax');
        }
    }
    // if we get here, then the window hasn't been created yet, or it
    // was closed by the user.
    if (test == 'test') {
        var urlDisplayID= "file.php?ID=" + id;
        window.open(urlDisplayID, 'width=' + screen.width, 'height=' + screen.height);
        test = 'tested';
    }
}

基本上,一次只允许窗口的一个实例,并且只显示第一个实例,而其他实例(不同的url -因为参数)通过AJAX发送到服务器。

根据你的情况,我想这也许是你需要的。

var openWindows = {};
function openwindowPreview(id) {
// if we get here, then the window hasn't been created yet, or it
// was closed by the user.
var urlDisplayID= "file.php?ID=" + id;
//set id as the window name, so if the window already opened,
//the open method will find the opened window with the window name
var opened =  window.open(urlDisplayID, id,'width=' + screen.width, 'height=' + screen.height);
if(opened === openWindows[id]){
    alert("ajax");
}else{
    openWindows[id] = opened();
}

}