【问题标题】:count the number of times an element has a specific style计算元素具有特定样式的次数
【发布时间】:2020-10-01 08:54:36
【问题描述】:

我试图计算一个元素具有特定类的次数。可悲的是我总是得到

$(...)[c].css 不是函数

jquery 是不是想欺负我?

这是我的代码:

// vanish the headings of the empty lists
let ulAll = document.querySelectorAll("ul.clearfix");
let counter = 0;

for(i = 0; i < ulAll.length; i++) {
    let ul = $(ulAll)[i].children;
    for(c = 0; c < ul.length; c++) {
        console.log($(ul)[c]);
        if($(ul)[c].css("display") == "none") {
            counter++;
            console.log(counter);
        }
    }
}

提前致谢!

【问题讨论】:

  • 使用jQuery的.eq()函数过滤索引:$(...).eq(c)

标签: javascript jquery for-loop


【解决方案1】:

对此的查找会减慢浏览器的渲染速度。 这是另一种方法。

首先像这样一次性获取所有的html:

var html = $('.parentOfContent').html();

然后在那个 html 上查找类:

const getClassCount = (html, myClass) => {
  const regMatchClass = RegExp('class\\=(\\"|\\"[^\\"]*\\s+)' + myClass + '(\\s|\\")', 'g');
  const count = 0;
  while(arrM = regMatchClass.exec(html)) {
    count +=1;
  }
  return count;
}
const html = $('.parentOfContent').html();
const myClass = 'clearfix';
const count = getClassCount(html, myClass);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-13
    • 1970-01-01
    • 2014-05-16
    • 2014-03-28
    • 2013-10-14
    相关资源
    最近更新 更多