如何使用 jQuery/Javascript 按类计算元素并将另一个类设置为列表中的某个元素。
有可能吗?
例如,我有四个类为“qa”的元素,并更改或添加类“qa2”列表中的第二个元素。
最佳答案
使用 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');
});
或者这将向所有具有类“cls”的元素添加“newClass”类
$('.cls').addClass('newClass');
或者这将为列表/匹配项目中的奇数和偶数项目添加不同的类
$('.cls').each(function(i){
if(!(i%2))
$(this).addClass('odd');
else
$(this).addClass('even');
});
关于javascript - jquery 按类计算元素并将另一个类设置为列表中的某个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9453995/