jQuery Get Random Element From a Selection Returned By $(selector)

前端 未结 3 2282

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

相关标签:
3条回答
  • 2021-02-20 10:36
    var numElements = $('.my-element').length;
    var randomNum = Math.floor(Math.random()*numElements);
    //Select your random element
    $('.my-element:nth-child(' + randomNum + ')');
    
    0 讨论(0)
  • 2021-02-20 10:37

    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
    
    0 讨论(0)
  • 2021-02-20 10:51
    $.fn.random = function() {
      return this.eq(Math.floor(Math.random() * this.length));
    }          
    
    $(selector).random();
    
    0 讨论(0)
提交回复
热议问题