收听多个子窗口关闭事件,无法检查多个孩子的窗口是否已关闭

时间:2017-05-17 16:29:21

标签: javascript c# asp.net

页面的父级正在侦听多个子窗口关闭事件。如果关闭了任何子窗口,则页面将在网格视图中进行回发。因此,不会重新加载父页面,并且window_dictionary不会重置'。在下面的代码中,我将窗口对象作为值添加到全局JavaScript字典中。该对象包含键(" clickedRow" +记录ID的组合),值为窗口对象。

对于第一个窗口关闭事件,它完全正常,但对于以下窗口关闭事件则没有。例如,如果我打开两个子窗口,我可以关闭第一个窗口,并且将调用__dopostback()方法,但是当我关闭剩余窗口时,则不会调用__dopostback()。

我假设setInterval调用可能存在问题。然而;我已经被困了一段时间,我无法按预期工作。

对于每个关闭的窗口,我都想做回发。

代码

    var openedWindows = {};

    setInterval(checkIfWindowIsClose, 40);

    function openThisWindow(popLoc, attributes, id) {
        var winInst = window.open(popLoc, attributes, id);
        openedWindows["clickedRow" + id] = winInst;
    }

    function checkIfWindowIsClose() {
        var id = "";
        for (var i in openedWindows) {

            if (openedWindows[i].closed) {
                // i is the id of your window and here you know that your window with id i has been closed
                // here remove also the window from the object otherwise you will keep also the instance of the closed one
                console.log(i);
                delete openedWindows[i];
                id = (' ' + i).slice(1);
                id = id.replace("clickedRow", "");

            }
        }
        if (id !== "") {

            __doPostBack('upInspectionList.UniqueID', id.toString());
            id = "";
        }

    }

谢谢

1 个答案:

答案 0 :(得分:1)

创建一个存储打开的窗口的对象。 在对象内部使用间隔周期,以检测窗口是否已关闭。 我试过它并且工作正常,当然可以根据您的所有需求更改此示例。 通过这种方式,您只需要一个计时器,而不是每次都创建一个计时器。

HTML:

<div>
    <button id="button-1" onclick="openThisWindow(this);">Button 1</button>
    <button id="button-2" onclick="openThisWindow(this);">Button 2</button>
    <button id="button-3" onclick="openThisWindow(this);">Button 3</button>
</div>

JS:

var openedWindows = {};

setInterval(checkIfWindowIsClose, 4);

function openThisWindow(el) {
    var winInst = window.open("http://www.google.it");
    openedWindows[el.id] = winInst;
}

function checkIfWindowIsClose() {
    for (var i in openedWindows) {
        if (openedWindows[i].closed) {
            // i is the id of your window and here you know that your window with id i has been closed
            // here remove also the window from the object otherwise you will keep also the instance of the closed one
            console.log(i);
            delete openedWindows[i];
        }
    }
}

有意义吗?