win1=不同函数中的window.open和win1.close()不起作用

win1 = window.open and win1.close() in different functions not working

本文关键字:win1 close 不起作用 open 函数 window      更新时间:2023-09-26

我在一个javascript中有两个独立的函数。

功能一用打开窗口

win1 = window.open (....);

功能二关闭窗口:

win1.close();

如果这些操作在一个函数中,则它正在工作,但不在如上所述的单独函数中。它以某种方式将对象win1从一个函数释放到另一个函数。

欢迎任何帮助!

您需要在两个函数之外声明win1变量,以便它们都在这两个函数的变量范围内。

var win1; // This variable is available in the variable scope of any 
          //    ...functions nested in the current scope.
function f1() {   // This function has access to its outer variable scope
    win1 = window.open();  //  ...so it can access the "win1" variable.
    var foo = 'bar'; // This variable is not available in the outer scope
}                    //   ...because it was declared inside this function.
function f2() {   // This function has access to its outer variable scope
    win1.close(); //  ...so it can access the "win1" variable.
    var bar = 'baz'; // This variable is not available in the outer scope
                     //   ...because it was declared inside this function.
    alert(foo); // Gives a ReferenceError, because "foo" is neither in the
                //   ...current, nor the outer variable scope.
}
f1(); // Invoke f1, opening the window.
f2(); // Invoke f2, closing the window.
alert(foo); // Would give a ReferenceError, because "foo" is in a nested scope.

您还可以全局定义win1

window.win1 = window.open(...);

您还可以声明一个全局变量。然后,您可以在脚本中的任何位置使用它。

var win = window.open("URL"); // or window.win = window
win.open();
win.close();

您必须将win1作为变量传递给这两个函数,或者将其置于这两个功能之外。

    function somethingHappened() {
        var url = "http://....";
        var win = window.open(url);
        one(win,url);
        two(win);
    }
function one(win,url) {
        win.open(url);

        }
        function two(win) {
        win.close();
        }