首页 > 解决方案 > 如何关闭通过单击javascript中的图像打开的新标签?

问题描述

我已经在 html 中编写了一个代码,该代码将在单击图像后在新选项卡中打开一个链接,但问题是我无法关闭该新窗口。

我想知道如何关闭那个新窗口??

<html>
<h1>Click on the image below to open google homepage </h1>

<head>
    <script>
        var x;
        var win = document.links;

        function closeFunc() {
            win[0].close();
        }
    </script>
</head>

<body>
    <a id="google" href="http://www.google.com" target="_blank">
        <img src="https://usercontent1.hubstatic.com/12498898_f520.jpg" alt="image" />
    </a>
    <br> <br>
    <button onclick="closeFunc()"> Close</button>
</body>

</html>

标签: javascripthtml

解决方案


试试这个

<html>
<h1>Click on the image below to open google homepage </h1>

<head>
    <script>
        var x;
        var win = document.links;

        function closeFunc() {
            win[0].close();
        }


           function popuponclick()
   {
      my_window = window.open("http://www.google.com",
       "mywindow");

   }

   function closepopup()
   {
      if(false == my_window.closed)
      {
         my_window.close ();
      }
      else
      {
         alert('Window already closed!');
      }
   }
    </script>
</head>

<body>
    <a id="google" href="javascript: popuponclick()" target="_blank">
        <img src="https://usercontent1.hubstatic.com/12498898_f520.jpg" alt="image" />
    </a>
    <br> <br>
    <button onclick="javascript: closepopup()"> Close</button>
</body>

</html>

推荐阅读