Редактировать: См. эту скрипку для чистого CSS решения.Не требует никакого JavaScript (используя селектор :nth-child
).
Используйте метод .index()
, чтобы получить индекс текущего элемента в коллекции элементов.Кроме того, поскольку .children()
возвращает объект jQuery, нет необходимости заключать countChildren
в $
.
. Для пояснения приведенный ниже код использует индексы, начинающиеся с 1 и -1 (как намекает наКод CSS).
Демо: http://jsfiddle.net/y7hBQ/18/
$(document).ready(function() {
$('.count, ul').each(function() {
var countChildren = $(this).children();
countChildren.filter(':even').addClass('even');
countChildren.filter(':odd').addClass('odd');
countChildren.first().addClass('first');
countChildren.last().addClass('last');
var numberOfChildren = countChildren.size();
countChildren.each(function(i){
var posindex = countChildren.index(this) + 1,
//^ This can be replaced by i + 1, for efficiency
negindex = numberOfChildren - posindex + 1;
$(this).addClass('nth-item-' + posindex)
.addClass('nth-item--' + negindex);
});
});
});