在多个浏览器Windows /选项卡中打开链接

时间:2009-11-15 14:04:30

标签: javascript jquery tabs window

我需要点击多个链接(选择它们),然后单击一个按钮,该按钮将打开新窗口或选项卡中的所有选定链接。这当然取决于浏览器的行为。

我的计划是使用Javascript将所选链接添加到数组中,然后在单击提交按钮时,javascript将在数组中运行并为每个项目打开一个新窗口。我可能会在jQuery中这样做。

有没有人做过类似的事情?还有其他选择吗?

2 个答案:

答案 0 :(得分:2)

我认为你是对的。

实现您所描述的恕我直言的最佳方法是使用return false;将要在新窗口中打开的链接的URL放入数组中,以防止实际打开链接然后使用某种循环打开所有这些。

我冒昧地将几行jQuery代码放在一起,这些代码将完成您所描述的内容:

$(document).ready(function() {
    var $hash = new Array(); // We create new Array 
    $('a').click( function(){ // On each click to <a> element
        if ( $(this).attr("data-pack") == "true" ) { // check wether this is one of the links we use
            $hash[$(this).attr("id")] = $(this).attr("href"); // We add href value into $hash object
            $(this).css("color","green"); // Way to mark selected ones
            $(this).attr("data-pack", "selected"); // Change data-pack property value to selected
            return false; // We don't want to execute this yet
        } else if ( $(this).attr("data-pack") == "selected" ) { // In case you change your mind and want to unselect
            $(this).attr("data-pack", "true"); // Change data-pack property back, thanks to Ambrosia pointing it out in the comment
            $(this).css("color","red"); // We mark it as unset
            delete $hash[$(this).attr("id")]; // Remove it from hash
            return false;
        }
    });

    $("form").submit( function(){ // After we submit
        for (var i in $hash) { // Go trough $hash
            window.open($hash[i]); // And open window for each member
        }
        return false; // We don't actually want to submit form, just open new windows :)
    } );    
});

HTML看起来像:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Page Title</title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js" type="text/javascript" charset="utf-8" async defer></script>
    <script src="application.js" type="text/javascript" charset="utf-8" async defer></script>
</head>
<body>
    <a href="#link1" data-pack="true" id="link1">data</a>
    <a href="#link2" data-pack="true" id="link2">data</a>
    <a href="#link3" data-pack="true" id="link3">data</a>
    <a href="#link4" data-pack="true" id="link4">data</a>
    <a href="#">ordinary link</a>

    <form>          
        <input type="submit" value="submit">
    </form>
</body>
</html>

答案 1 :(得分:0)

我认为最简单的方法是使用锚标记的target="_blank"属性。通过它创建<a>元素和.click的集合。

理论上你可以使用window.open但是这个方法会打开一个新窗口而不是你想要的新TAB。

相关问题