页面跳转的两种方法

Onclick 跳转

window.location.href="URL";//覆盖当前页
window.open("URL","_blank");//新窗口打开
window.open("URL","_self");//覆盖当前页

若一直通过新窗口打开,会打开很多相同的页面,根据当前页面是否打开决定是新开标签页还是跳转:

window.open("URL","PageTitle");

上述代码存在问题:

  • Firefox 下存在兼容性问题,对已打开的页面不能成功跳转!!!

解决方案:

const winRef=window.open("URL","PageTitle");
winRef.focus(); // 兼容 Firefox 无法跳转问题

a 标签跳转

<!--新窗口打开-->
<a href="URL" target="_blank"></a>
<!--覆盖当前页-->
<a href="URL" target="_self"></a>

a 标签下实现页面不重复的打开:

<!--覆盖当前页-->
<a href="URL" target="PageTitle"></a>

上述方案无需考虑兼容性。

注意:PageTitle 为当前页面的 title,URL为当前页面的链接。

DEMO

目录结构:

image-20200716201741837

a.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Page1</title>
</head>
<body>
    <a href="b.html" target="Page2">Page a</a>
    <button onclick={openWin()}>openWindow</button>
    <script>
        function openWin(){
            const ref=window.open("b.html","Page2");
            ref.focus();
        }
    </script>
</body>
</html>

b.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Page2</title>
</head>
<body>
    <a href="a.html" target="Page1">Page b</a>
    <button onclick={openWin()}>openWindow</button>
    <script>
        function openWin(){
            const ref=window.open("a.html","Page1");
            ref.focus();
        }
    </script>
</body>
</html>