gpt4 book ai didi

javascript - 如何计算具有特定类jquery的元素

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:59:38 25 4
gpt4 key购买 nike

我有类元素,如 dis_5dis_3 。这里 dis_ 部分保持不变,而数字发生变化。我想计算每个 dis 编号的元素,例如,如果 3 个元素具有 dis_5 类,则计算元素。其他人也同样如此。

var result = $('[class^=dis_]').filter(function () {
return this.class.match(/dis_\d+$/); //regex for the pattern "rank_ followed by a number"
});

如何将末尾带有特定编号的元素捆绑在一起。

最佳答案

试试这个,

var classes={};
$('[class^=dis_]').each(function () {
if(classes.hasOwnProperty(this.className)){
classes[this.className]= classes[this.className]+1;
} else {
classes[this.className]=1;
}
});

片段,

var classes = {};
$('[class^=dis_]').each(function() {
if (classes.hasOwnProperty(this.className)) { // if classs exists then increment it by 1
classes[this.className] = classes[this.className]+1;
} else {
classes[this.className] = 1; // first instance
}
});
console.log(classes);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="dis_1">Class 1</div>
<div class="dis_1">Class 1</div>
<div class="dis_1">Class 1</div>
<div class="dis_5">Class 5</div>
<div class="dis_5">Class 5</div>
<div class="dis_2">Class 2</div>
<div class="dis_3">Class 3</div>

如果您有多个类(class),请尝试下面的片段

var classes = {};
$('[class*=dis_]').each(function() { // use *= selector, dis_ class can be used anywhere
className = null;
// get all classes and split to get match for dis_
$.each($(this).attr('class').split(/\s+/), function(index, cls) {
if (/dis_\d+/.test(cls)) {
className = cls;
}
});
// check if element having class started with dis_
if (className) {
if (classes.hasOwnProperty(className)) { // if classs exists then increment it by 1
classes[className] = classes[className] + 1;
} else {
classes[className] = 1; // first instance
}
}
});
console.log(classes);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="dis_1">Class 1</div>
<div class="dis_1">Class 1</div>
<div class="dis_1 rehub_meta_field rehub_field_1 disabled disabled-0">Class 1</div>
<div class="dis_5">Class 5</div>
<div class="dis_5">Class 5</div>
<div class="dis_2">Class 2</div>
<div class="rehub_meta_field rehub_field_1 disabled disabled-0 dis_3">Class 3</div>

关于javascript - 如何计算具有特定类jquery的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43580487/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com