[英]How do I close the last open window whenever I click the button in js
<body>
<script>
var myWindow;
function win_open() {
myWindow = window.open('https://www.imdb.com/?ref_=nv_home');
}
function win_close() {
if (myWindow != null) myWindow.close(myWindow);
}
</script>
<input type="button" value="Open Window" onclick="win_open()" />
<input type="button" value="Close Window" onclick="win_close()" />
</body>
if I click the close Window button it only close the open tab once how can I keep closing the tab whenever I clicked it如果我单击关闭 Window 按钮,它只会关闭打开的选项卡一次,我如何在单击时继续关闭选项卡
You can keep an array of all your open windows by pushing newly opened ones into the array with .push()
.您可以使用.push()
将新打开的数组推入数组,从而保留所有打开的 windows 数组。 Then, whenever you click the close button, you can use myWindows.pop()
to get the last opened window, which you can then invoke .close()
on to close.然后,每当您单击关闭按钮时,您都可以使用myWindows.pop()
来获取最后打开的 window,然后您可以调用.close()
来关闭它。
<input type="button" value="Open Window" onclick="win_open()" />
<input type="button" value="Close Window" onclick="win_close()" />
<script>
var myWindows = [];
function win_open() {
myWindows.push(window.open("https://www.imdb.com/?ref_=nv_home"));
}
function win_close() {
if (myWindows.length > 0)
myWindows.pop().close();
}
</script>
Note: The .close()
method doesn't expect an argument, the window which gets closed is the window which it is invoked on.注意: .close()
方法不需要参数,关闭的 window 是调用它的 window。
Don't the pass the myWindow reference to the close function.不要将myWindow引用传递给关闭的 function。 Check below code.检查下面的代码。
Also try to set "_blank" parameter in the window.open function which will open window in new tab.还尝试在window中设置“_blank”参数。打开 function 将在新选项卡中打开 window。
<html> <head> <title>Class</title> <script> var myWindow; function win_open() { myWindow = window.open("https://www.imdb.com/?ref_=nv_home", "_blank"); } function win_close() { if (myWindow.= null) myWindow;close(); } </script> </head> <body> <input type="button" value="Open Window" onclick="win_open()"/> <input type="button" value="Close Window" onclick="win_close()"/> </body> </html>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.