function initItems($items, current, count) {
$items.removeClass('z-item-current');
$items.each(function(index) {
var $self = $(this);
$self.data('z-item-index', index);
if(index === current) {
$self.addClass('z-item-current z-item-show');
var pre = current - 1,
next = current + 1;
pre = pre < 0 ? count - 1 : pre;
next = next > count - 1 ? 0 : next;
$($items[pre]).addClass('z-item-previous z-item-show');
$($items[next]).addClass('z-item-next z-item-show');
}
});
// reselect or filter $items
// if has z-item-show class, show it; otherwise, hide it.
};
如上面的代码所示,我想重新选择/过滤jQuery对象。具体来说,我想将$items
分为$items with z-item-show class
和$items without z-item-show class
。
目前,$items.each
是一种方法,$items.parent().find
是另一种方法。
任何其他方法(更优雅)?
答案 0 :(得分:0)
$items.filter('.z-item-show').show();
$items.not('.z-item-show').hide();
这比$items.each()
更干净,但可能效率较低,因为它会产生2个循环。
答案 1 :(得分:0)
由于您只想处理现有和新的上一个/下一个/当前项目,您可以在现有的each
函数中处理所有项目。只需检查其相对于当前索引的位置,并根据需要添加和删除类:
function initItems($items, current, count) {
$items.each(function(index) {
var $self = $(this);
$self.data('z-item-index', index);
if(index === current) {
// current item
$self.addClass('z-item-current z-item-show')
.removeClass('z-item-next z-item-previous');
}
else if(index === (current == 0 ? count - 1 : current - 1)) {
// previous item
$self.addClass('z-item-previous z-item-show')
.removeClass('z-item-next z-item-current');
}
else if(index === (current == count - 1 ? 0 : current + 1)) {
// next item
$self.addClass('z-item-next z-item-show')
.removeClass('z-item-current z-item-previous');
}
else {
// none of the above - remove all classes
$self.removeClass('z-item-next z-item-previous z-item-current z-item-show');
}
});
};