最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Uncaught TypeError: Cannot read property 'close' of undefined - Stack Overflow

programmeradmin4浏览0评论

When i pile the following code , it works fine , but in console i get error: 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("", "myWindow");
}


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

</body>
</html>

When i pile the following code , it works fine , but in console i get error: 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.", "myWindow");
}


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

</body>
</html>

var myWindow;

function openWin(){


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


function closeWin() {
    myWindow.close();

}

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

Share Improve this question edited Sep 3, 2015 at 9:28 mahesh asked Sep 3, 2015 at 9:27 maheshmahesh 391 gold badge1 silver badge11 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 5

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

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

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

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

发布评论

评论列表(0)

  1. 暂无评论