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

时间:2012-02-04 17:11:07

标签: javascript

我在javascript中有2个单独的函数。

功能一打开一个带

的窗口
win1 = window.open (....);

功能二关闭窗口:

win1.close();

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

非常欢迎任何帮助!

3 个答案:

答案 0 :(得分:3)

您需要在两个函数之外声明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.

答案 1 :(得分:0)

您还可以全局定义win1

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

答案 2 :(得分:0)

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

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

        }