JavaScript/jQuery 不支持以编程方式“点击”链接的默认行为。
相反,您可以创建一个表单并提交它。这样您就不必使用window.location或window.open,它们通常被浏览器阻止为不需要的弹出窗口。
该脚本有两种不同的方法:一种尝试打开三个新选项卡/窗口(它只在 Internet Explorer 和 Chrome 中打开一个,更多信息如下),另一种在链接点击时触发自定义事件。
方法如下:
HTML
<html>
<head>
    <script src="jquery-1.9.1.min.js" type="text/javascript"></script>
    <script src="script.js" type="text/javascript"></script>
</head>
<body>
    <button id="testbtn">Test</button><br><br>
    <a href="https://google.nl">Google</a><br>
    <a href="http://en.wikipedia.org/wiki/Main_Page">Wikipedia</a><br>
    <a href="https://stackoverflow.com/">Stack Overflow</a>
</body>
</html>
jQuery(文件script.js)
$(function()
{
    // Try to open all three links by pressing the button
    // - Firefox opens all three links
    // - Chrome only opens one of them without a popup warning
    // - Internet Explorer only opens one of them WITH a popup warning
    $("#testbtn").on("click", function()
    {
        $("a").each(function()
        {
            var form = $("<form></form>");
            form.attr(
            {
                id     : "formform",
                action : $(this).attr("href"),
                method : "GET",
                // Open in new window/tab
                target : "_blank"
            });
            $("body").append(form);
            $("#formform").submit();
            $("#formform").remove();
        });
    });
    // Or click the link and fire a custom event
    // (open your own window without following 
    // the link itself)
    $("a").on("click", function()
    {
        var form = $("<form></form>");
        form.attr(
        {
            id     : "formform",
            // The location given in the link itself
            action : $(this).attr("href"),
            method : "GET",
            // Open in new window/tab
            target : "_blank"
        });
        $("body").append(form);
        $("#formform").submit();
        $("#formform").remove();
        // Prevent the link from opening normally
        return false;
    });
});
对于每个链接元素,它:
- 创建表单
 
- 赋予它属性
 
- 将其附加到 DOM 以便提交
 
- 提交
 
- 从 DOM 中移除表单,移除所有痕迹 *插入邪恶的笑声*
 
现在你有一个新的标签/窗口加载"https://google.nl"(或任何你想要的 URL,只需替换它)。不幸的是,当您尝试以这种方式打开多个窗口时,您会Popup blocked在尝试打开第二个窗口时收到一个消息栏(第一个仍然打开)。
有关我如何使用此方法的更多信息,请参见此处: