我认为这是一个简单的问题,但我是JavaScript新手
当我尝试关闭一个新窗口时,为什么按钮"but2"不起作用?
HTML代码
<input type="button" value="New window" id="but1" onclick="createwin()" />
<input type="button" value="close window" id="but2" onclick="closewin()" />
Run Code Online (Sandbox Code Playgroud)
JavaScript代码
function createwin(){
var win1 = window.open('http://www.google.com','google','width=500,height=500');
}
function closewin(){
win1.close();
}
Run Code Online (Sandbox Code Playgroud)
它的范围问题win1变量超出了范围.由于您在createwin()函数中声明了win1,因此closewin()函数没有引用,它超出了范围.您需要将win1设置为全局变量,如下所示:
var win1;
function createwin(){
win1 = window.open('http://www.google.com','google','width=500,height=500');
}
function closewin(){
win1.close();
}
Run Code Online (Sandbox Code Playgroud)
您的变量范围已关闭:
// Note I don't use var here to declare
// the win1, which makes it globally available
// instead of just function-scope available.
function createwin(){
win1 = window.open('http://www.google.com','google','width=500,height=500');
}
function closewin(){
// Do this to prevent Javascript errors.
if (win1 && win1.close && typeof win1.close == 'function') {
win1.close();
}
}
Run Code Online (Sandbox Code Playgroud)
http://jsfiddle.net/userdude/h7VjC/2/
在Javascript中声明变量时,您必须知道如何声明它们.
请看这里有一个很好的演示:JavaScript中的变量范围是什么?