简体   繁体   English

jQuery使用正则表达式查找具有可变类名称的元素?

[英]jQuery find elements with variable class names using regex?

I am trying to get the number of elements that have a certain class name in them, the problem is, this class name has a variable at the end of it. 我试图获取其中具有特定类名的元素的数量,问题是,该类名的末尾有一个变量。 For example: 例如:

<div class="row">
    <div class="col">

    </div>
    <div class="col width-33">

    </div>
    <div class="col">

    </div>
</div>

I have been trying to write a jquery script to get the number of different col s there are and to get the number of columns with a class name of width-xx where XX can be any number. 我一直在尝试编写一个jquery脚本来获取存在的不同col的数量,并获取具有width-xx的类名的列数,其中XX可以为任何数字。

$('.col').parent().each(function(i){ //The container could be anything
    var numCols = $(this).children('.col').length;
    var numColsWidth = $(this).children('div[class^="width-"].col').length;
    console.log(numCols, numColsWidth);
});

I'd like to output to be 3 1 , showing there are 3 total columns and 1 of them has a class named width-xx. 我想输出为3 1 ,显示总共有3列,其中1列名为width-xx。

Just as the example above shows, I've tried using the CSS selector, but that doesn't give me anything (outputs 3 0 ) 就像上面的示例所示,我已经尝试使用CSS选择器,但这并没有给我任何东西(输出3 0

I've also tried playing around with RegExp, but I'm not sure how to add this into that 我也尝试过使用RegExp,但不确定如何将其添加到RegExp中

var widthClass = new RegExp("width-");
if(widthClass.test($('.col').attr('class'))){
    //do something
}

So, all I would like to do is count the number of elements that contain the word "width-" in the class. 因此,我要做的就是计算类中包含单词“ width-”的元素的数量。

$('[class*="width-"]').length should do it. $('[class*="width-"]').length应该可以做到。
this selector allows you to find any element that countains the word "width-" in the class 该选择器使您可以找到该类中包含单词“ width-”的任何元素

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

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