我有一系列类.random-related
的元素。在任何给定的时间都有一个可变数量的这个类,但它大约有15到20个元素。我要做的是采取两个随机的例子,然后.hide()
。
我正在考虑做$('.random-related').toArray()
这样的事情,使用预先编写的shuffle函数对该数组进行混洗,然后选择索引0和1.但是,我不知道如何将数组转换回一组然后我可以遍历jQuery对象并应用任何方法。
最好的方法是什么?
答案 0 :(得分:0)
function shuffle(a) {
var j, x, i;
for (i = a.length - 1; i > 0; i--) {
j = Math.floor(Math.random() * (i + 1));
x = a[i];
a[i] = a[j];
a[j] = x;
}
return a
}
var randomRelated = shuffle($('.random-related').toArray());
randomRelated.forEach(element => {
if(randomRelated.indexOf(element) == 0 || randomRelated.indexOf(element) == 1 ){
return
}
element.style.display = 'none'
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="random-related">1</p>
<p class="random-related">2</p>
<p class="random-related">3</p>
<p class="random-related">4</p>
<p class="random-related">5</p>
<p class="random-related">6</p>
<p class="random-related">7</p>
<p class="random-related">8</p>
<p class="random-related">9</p>
<p class="random-related">10</p>
答案 1 :(得分:0)
使用jquery built-int选择器eq
和not
以及两个随机索引。
var randomize = function(howMany) {
var a = Math.floor(Math.random() * howMany),
b;
do {
b = Math.floor(Math.random() * howMany);
} while (b === a);
var max = Math.max(a, b);
var min = Math.min(a, b);
var $selection2Hide = $('#wrapper div:not(.random-related:eq(' + (min - 1) + '), .random-related:eq(' + (max - 1) + '))');
$selection2Hide.hide();
var $selection = $('#wrapper div.random-related:eq(' + (min - 1) + '), div.random-related:eq(' + (max - 1) + ')');
$selection.each(function() {
console.log('Do stuff with = ' + $(this).html());
});
};
randomize($('.random-related').size());
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='wrapper'>
<div class='random-related'>1</div>
<div class='random-related'>2</div>
<div class='random-related'>3</div>
<div class='random-related'>4</div>
<div class='random-related'>5</div>
<div class='random-related'>6</div>
<div class='random-related'>7</div>
<div class='random-related'>8</div>
<div class='random-related'>9</div>
<div class='random-related'>10</div>
<div class='random-related'>11</div>
<div class='random-related'>12</div>
<div class='random-related'>13</div>
<div class='random-related'>14</div>
<div class='random-related'>15</div>
</div>
&#13;