How to get random element in jquery?

后端 未结 7 1637
悲&欢浪女
悲&欢浪女 2020-12-03 01:04

How can I return a random element in jQuery by doing something like $(.class).random.click()?

So, if .class had 10 links, it would randomly

相关标签:
7条回答
  • 2020-12-03 01:12

    You can write a custom filter (taken from here):

    jQuery.jQueryRandom = 0;
    jQuery.extend(jQuery.expr[":"], {
        random: function(a, i, m, r) {
            if (i == 0) {
                jQuery.jQueryRandom = Math.floor(Math.random() * r.length);
            };
            return i == jQuery.jQueryRandom;
        }
    });
    

    Example usage:

    $('.class:random').click()
    

    The same thing but as a plugin instead:

    ​jQuery.fn.random = function() {
        var randomIndex = Math.floor(Math.random() * this.length);  
        return jQuery(this[randomIndex]);
    };
    

    Example usage:

    $('.class').random().click()
    
    0 讨论(0)
  • 2020-12-03 01:13

    randojs.com makes this a simple one-liner:

    rando($("a")).value[0].click()
    

    The ".value" is there because you also have the option to get the index of the random jQuery element. The "[0]" is there to turn the jQuery element into a plain JavaScript element. If you add the following to the head of your html document, you can do pretty much whatever you want with randomness easily. Random values from arrays, random jquery elements, random properties from objects, and even preventing repetitions if needed.

    <script src="https://randojs.com/1.0.0.js"></script>
    
    0 讨论(0)
  • 2020-12-03 01:19

    I'd suggest doing it the jQuery way using .eq() and .trigger().

    $elements.eq(Math.floor(Math.random() * $elements.length)).trigger('click');
    
    0 讨论(0)
  • 2020-12-03 01:24

    You can select random item by class name using jquery method eq()

    see the example bellow.

    var len = $(".class").length
    var random = Math.floor( Math.random() * len ) + 1;
    $(".class").eq(random).click();
    
    0 讨论(0)
  • 2020-12-03 01:26

    If you don't want to hard code the number of elements to choose from, this works:

    things = $('.class');
    $(things[Math.floor(Math.random()*things.length)]).click()
    
    0 讨论(0)
  • 2020-12-03 01:32
    var random = Math.floor(Math.random()*10);
    $(".someClass").eq(random).click();
    
    0 讨论(0)
提交回复
热议问题