jQuery Get Random Element From a Selection Returne

2019-04-06 04:01发布

问题:

If $('.my-element') matches multiple element, is there a quick way to get a random element out of these?

回答1:

$.fn.random = function() {
  return this.eq(Math.floor(Math.random() * this.length));
}          

$(selector).random();


回答2:

To get an even distribution, you can multiply random by the array count and drop the decimal with the bitwise operator.

var arr = ['a','b','c'];
arr[~~(Math.random() * arr.length)]; //even odds of a, b, or c


回答3:

var numElements = $('.my-element').length;
var randomNum = Math.floor(Math.random()*numElements);
//Select your random element
$('.my-element:nth-child(' + randomNum + ')');


标签: jquery random