【发布时间】:2013-11-19 02:52:38
【问题描述】:
我想要一个按钮,可以从 jQuery 中未排序的 HTML 列表中随机选择 5 个列表项。我还想确保该函数首先确保如果有 5 个或更少的列表项,它将简单地选择所有可用的列表项。另外,我想确保随机 5 在其数组中没有重复项。另外,假设有 28 个列表项,我希望它随机选择 5 个尚未选择的项,因为您可以多次单击该按钮。所以基本上我想随机选择 5 个,直到整个列表都被选中。这是我目前所拥有的。
<ul id="masterlist">
<li><a href="http://www.example1.com" target="_blank">Example 1</a></li>
<li><a href="http://www.example2.com" target="_blank">Example 2</a></li>
<li><a href="http://www.example3.com" target="_blank">Example 3</a></li>
<li><a href="http://www.example4.com" target="_blank">Example 4</a></li>
<li><a href="http://www.example5.com" target="_blank">Example 5</a></li>
<li><a href="http://www.example6.com" target="_blank">Example 6</a></li>
<li><a href="http://www.example7.com" target="_blank">Example 7</a></li>
<li><a href="http://www.example8.com" target="_blank">Example 8</a></li>
<li><a href="http://www.example9.com" target="_blank">Example 9</a></li>
</ul>
<button id="openfiverandom">Open 5 Random</button>
<script type="text/javascript">
$(function() {
$('#openfiverandom').bind('click', function(event) {
var links = $('#masterlist li a');
var len = links.length;
if (len <= 5) {
$('#masterlist li a').each( function() { this.click(); })
}
else {
while(links.length > 5) {
links.eq(parseInt(len * Math.random())).hide();
}
links.each( function() { this.click(); })
}
});
});
</script>
它不起作用,也不检查重复项。我希望在stackoverflow上找到更好的解决方案。还要记住链接有 target="_blank" 这意味着它们仍然会全部打开,它不会在第一个停止,因为它不会转发当前页面。我还在想,简单地随机化主列表数组,然后对前五个进行切片可能会更容易。不过不知道该怎么做。
【问题讨论】:
-
注意触发点击不会打开链接
-
事实上,@charlietfl 确实如此。它适用于我拥有的另一个功能。
-
不跨浏览器它不会。安全功能,因此人们不会随意打开各种东西(至少它以前不工作)
-
确实如此。在 Chrome 中,它会在新标签页中打开一个链接,其余的则在各自的窗口中打开。在 Firefox 中,它会打开所有新标签(这是我想要的)
-
然后在 IE 中尝试...过去无法跨浏览器执行此操作...也许浏览器供应商已经改变了一些事情...我很惊讶。使用更安全
window.open