【问题标题】:jquery count the elements by class and set the another class a certain element in the listjquery按类计算元素并将另一个类设置为列表中的某个元素
【发布时间】:2012-03-16 06:36:22
【问题描述】:

如何使用 jQuery/Javascript 按类计算元素并将另一个类设置为列表中的某个元素。

有可能吗?

例如,我有四个“qa”类元素,并在列表中更改或添加“qa2”类第二个元素。

【问题讨论】:

标签: javascript jquery


【解决方案1】:

相对容易:

var numOfElementsOfClassName = $('.classNameToFind').length;
var particularIndexToApplyNewClass = 3;
$('.classNameToFind').eq(particularIndexToApplyNewClass).addClass('newClassName');

参考资料:

【讨论】:

  • 也许需要用removeClass()删除旧类。
  • 我考虑过,但我无法从最初的问题(比如它是)应该添加新类还是替换旧类。
  • 你没有提供任何细节。你想找到什么元素。您要向哪个元素添加类名?你的标记是什么?您要更改类名,还是附​​加另一个类名?
  • 感谢大卫的回复。我只需要: var el = $('.qa'); $(el[1]).addClass('qa2');
【解决方案2】:

使用 jquery

var el = $('.cls');
alert(el.length); // Will alert length

向第二个元素添加一个类

$(el[1]).addClass('classOne'); // first item is 0 and second item is 1 and so on

在循环中使用条件将类添加到第二个元素。

el.each(function(i){
    if(i==1) // If 2nd item then add the class
        $(el[i]).addClass('newClass');  
});​

或者这会将“newClass”类添加到所有具有类“cls”的元素

$('.cls').addClass('newClass')​; 

或者这将为列表/匹配项中的奇数项和偶数项添加不同的类

​$('.cls').each(function(i){
    if(!(i%2))  
        $(this).addClass('odd');
    else
        $(this).addClass('even');
});​

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-08-30
    • 1970-01-01
    • 1970-01-01
    • 2018-01-29
    • 2021-10-24
    • 2013-11-16
    • 1970-01-01
    相关资源
    最近更新 更多