javascript 未捕获的类型错误:无法读取未定义的属性“关闭”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32371804/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 15:10:31  来源:igfitidea点击:

Uncaught TypeError: Cannot read property 'close' of undefined

javascripthtml

提问by mahesh

When i compile the following code , it works fine , but in console i get error: Uncaught TypeError: Cannot read property 'close' of undefined

当我编译以下代码时,它工作正常,但在控制台中我收到错误:Uncaught TypeError: Cannot read property 'close' of undefined

<!DOCTYPE html>
<html>
<body>

<button onclick="openWin()">Open "myWindow"</button>
<button onclick="closeWin()">Close "myWindow"</button>

<script>
var myWindow;

function openWin(){
   myWindow = window.open("http://www.w3schools.com", "myWindow");
}


function closeWin() {
    myWindow.close();
}
</script>

</body>
</html>

var myWindow;

function openWin(){


    myWindow = window.open("http://www.w3schools.com/", "myWindow");
 
}


function closeWin() {
    myWindow.close();

}

i tried to call the above js file externally also, i get the same error

我也尝试在外部调用上述 js 文件,但出现相同的错误

回答by slomek

You have to click Open "myWindow"button before clicking the other one, because that is when the variable myWindow gets initial value.

您必须Open "myWindow"在单击另一个按钮之前单击按钮,因为那是变量 myWindow 获得初始值的时候。

You should check if window has been opened before trying to close it:

在尝试关闭窗口之前,您应该检查窗口是否已打开:

function closeWin() {
    if(myWindow){
        myWindow.close();
    }
}

If myWindowis not set, you just do nothing (as there is nothing to be closed, right?).

如果myWindow没有设置,你什么都不做(因为没有什么可以关闭的,对吧?)。