关闭所有弹出窗口

Dav*_*vid 1 javascript jquery popup

我知道这个问题有很多问题有许多答案.

我知道我可以用

var popup = window.open('');
Run Code Online (Sandbox Code Playgroud)

以后可以用

popup.close();
Run Code Online (Sandbox Code Playgroud)

关闭那个窗口.

但是,有没有办法关闭所有孩子而不必存储window.open结果?

那就是我能做到的

window.open('1');
window.open('2');
window.open('3');
Run Code Online (Sandbox Code Playgroud)

然后以某种方式做一个关闭这三个窗口的全局"关闭"调用?

如果没有,我可以通过使用以下代码来完成它吗?

window.open('1','window1');
window.open('2','window2');
window.open('3','window3');
Run Code Online (Sandbox Code Playgroud)

Aus*_*rst 6

您可以创建一个新功能,基本上将现有功能包装在您尝试执行的操作中.

var WindowDialog = new function() {
    this.openedWindows = {};

    this.open = function(instanceName) {
        var handle = window.open(Array.prototype.splice.call(arguments, 1));

        this.openedWindows[instanceName] = handle;

        return handle;
    };

    this.close = function(instanceName) {
        if(this.openedWindows[instanceName])
            this.openedWindows[instanceName].close();
    };

    this.closeAll = function() {
        for(var dialog in this.openedWindows)
            this.openedWindows[dialog].close();
    };
};
Run Code Online (Sandbox Code Playgroud)

样本用法

WindowDialog.open('windowName', /* arguments you would call in window.open() */);
WindowDialog.open('anotherName', /* ... */);
WindowDialog.open('uniqueWindow', /* ... */);
WindowDialog.open('testingAgain', /* ... */);
WindowDialog.open('finalWindow', /* ... */);

// closes the instance you created with the name 'testingAgain'
WindowDialog.close('testingAgain');

// close all dialogs
WindowDialog.closeAll();
Run Code Online (Sandbox Code Playgroud)