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 + ')');