我很抱歉这个问题的形式。我知道应该包括一些代码,但我甚至不知道从哪里开始。我需要找到在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>如何找到子类的总数-1(在本例中?)。类是动态生成的,我从不知道每次哪个类最常见。
发布于 2015-03-23 03:59:16
您可以从下面的代码中找到类的完整列表及其计数。
var classes = new Object();
$("*").each(function() {
if (this.className.length > 0)
{
var arrTmp = this.className.split(" ");
for (var i=0; i<arrTmp.length; i++)
{
if ($.trim(arrTmp[i]).length > 0)
{
if (classes[arrTmp[i]])
classes[arrTmp[i]] = classes[arrTmp[i]] + 1;
else
classes[arrTmp[i]] = 1;
}
}
}
});
var sortable = [];
for (var arr in classes)
sortable.push([arr, classes[arr]])
sortable.sort(function(a, b) {return b[1] - a[1]});
alert(sortable);在JsFiddle:https://jsfiddle.net/qsfdm286/上的测试
发布于 2015-03-23 03:42:06
你可以的
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)演示:小提琴
如果你也想考虑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)演示:小提琴
发布于 2015-03-23 03:40:42
当您了解该类时,您可以按以下方式查找该类的用法:
var classList = document.getElementById('divId').className.split(/\s+/);
for (var i = 0; i < classList.length; i++) {
var numItems = $('.'+classList[i]).length;
console.log('Usage of class ' classList[i] 'is ' numItems )
}https://stackoverflow.com/questions/29202888
复制相似问题