jQuery Get Random Element From a Selection Returne

2019-04-06 03:46发布

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

标签: jquery random
3条回答
不美不萌又怎样
2楼-- · 2019-04-06 04:22

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楼-- · 2019-04-06 04:28
$.fn.random = function() {
  return this.eq(Math.floor(Math.random() * this.length));
}          

$(selector).random();
查看更多
姐就是有狂的资本
4楼-- · 2019-04-06 04:28
var numElements = $('.my-element').length;
var randomNum = Math.floor(Math.random()*numElements);
//Select your random element
$('.my-element:nth-child(' + randomNum + ')');
查看更多
登录 后发表回答