在多个浏览器窗口/选项卡中打开链接
我需要单击多个链接(将其选中),然后单击一个按钮,该按钮将在新窗口或选项卡中打开所有选定的链接.当然,这取决于浏览器的行为.
I have a requirement to click on multiple links (selecting them) and then click a button that will open all selected links in new windows or tabs. This will of course be dependent upon the browser behaviour.
我的计划是使用Javascript将选定的链接添加到数组,然后单击提交"按钮,JavaScript将在数组中运行并为每个项目打开一个新窗口.我可能会在jQuery中做到这一点.
My plan is to use Javascript to add the selected links to an array and then upon clicking the submit button, the javascript will run through the array and open a new window for each item. I will probably do this in jQuery.
有人做过类似的事情吗?有其他选择吗?
Has anyone done anything similar? Are there alternatives?
我认为您是对的.
实现IMHO描述的最佳方法是使用return false;
将要在新窗口中打开的链接的URL放入数组中,以防止实际打开链接,然后使用某种循环来打开所有这些.
The best way to achieve what you are describing IMHO is to place URL's of links you want to open in new windows into an array, using return false;
in order to prevent actually opening link and then to use some sort of loop to open all of them.
我*地将几行jQuery代码组合在一起,以完成您所描述的事情:
I took a liberty of putting together few lines of jQuery code that will do what you have described:
$(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>