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

时间:2013-04-24 04:32:28

标签: javascript popup global-variables

第一次来这里。我正在尝试使用Javascript对这些功能进行编码。

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

但是,如果单击第二个链接,并且存在一个现有的弹出窗口,它将运行一些AJAX功能。我们不会导航到该链接。

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

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

这是我的jsfiddle

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发送到服务器。

1 个答案:

答案 0 :(得分:0)

在你的情况下,我认为这可能是你的需要。

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();
}

}