gpt4 book ai didi

javascript - 找到一个最常见的类

转载 作者:行者123 更新时间:2023-11-28 00:28:58 25 4
gpt4 key购买 nike

我对这个问题的格式感到抱歉。我知道应该包含一些代码,但我什至不知道从哪里开始。我需要在 div 与另一个类中找到最常见的类,包含某个符号。问题是找到最常见的一个。

假设有很多 div

<div class="mainclass subclass-1 subclass1"></div>
<div class="mainclass subclass-1 subclass3"></div>
<div class="mainclass subclass-2 subclass3"></div>
<div class="mainclass subclass-1 subclass2"></div>
<div class="mainclass subclass-1 subclass1"></div>

我如何找到 subclass-1 的总数(在本例中?)。类是动态生成的,我永远不知道每次哪个类是最常见的。

最佳答案

你可以

var counter = {}, //to store the count of occurences temporarely
max; //the most common class
//iterate over te main class
$('.mainclass').each(function () {
//find the subclass-* value
var cs = this.className.match(/subclass-\d+/)[0];
counter[cs] = counter[cs] || 0;
//increment the count of occurrence
counter[cs]++;
if (counter[cs] > (counter[max] || 0)) {
//if the current one is more then change the max to current class
max = cs;
}
});
console.log(max)

演示:Fiddle

<小时/>

如果您也想考虑subclass1,那么

var counter = {}, //to store the count of occurences temporarely
max; //the most common class
//iterate over te main class
$('.mainclass').each(function () {
//find the subclass-* value
var parts = this.className.match(/subclass-?\d+/g);
$.each(parts, function (i, cs) {
counter[cs] = counter[cs] || 0;
//increment the count of occurrence
counter[cs]++;
if (counter[cs] > (counter[max] || 0)) {
//if the current one is more then change the max to current class
max = cs;
}
})
});
console.log(max, counter)

演示:Fiddle

关于javascript - 找到一个最常见的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29202888/

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