简体   繁体   English

如何获取具有特定class属性的所有HTML元素?

[英]How to get all HTML elements with a certain class attribute?

I need to get all elements that use a certain class and choose a random one. 我需要获取使用某个类的所有元素,然后选择一个随机的类。

How can I do this in jQuery? 如何在jQuery中做到这一点?

var random_elem = $('.yourclass').eq(Math.floor(Math.random()*$('.yourclass').length));

Try this: 尝试这个:

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;
    }
});

var randomElem = $(".className:random");

Orig article: http://blog.mastykarz.nl/jquery-random-filter/ 原始文章: http : //blog.mastykarz.nl/jquery-random-filter/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM