select a range of dom elements based on index
I need to select a specific grange of jquery elements based on there index using :eq()
(or something else if you have a better solution)
my html structure is the following:
<ul>
<li>slide0</li>
<li>slide1</li>
<li>slide2</li>
<li>slide3</li>
<li>slide4</li>
</ul>
When开发者_如何学JAVA the user hovers slides over the slide2 i need to select li:eq(0), li:eq(1)
and li:eq(3), li:eq(4)
separatly, because they have a different animation.
This is my solution, but this feels a little messy...
var $slides, theOthers, slidesTotal;
$slides = $('ul > li');
slidesTotal = $slides.length;
theOthers = function(slideIndex ,slidesTotal){
var before = [], after = [], i=0;
while (i<=slideIndex - 1){
before[i] = ":eq(" + i + ")"
i++
};
while (i <= slidesTotal) {
after[i] = ":eq(" + i + ")"
i++
};
return [ before.join(",") , after.join(",") ]
}
$slides.mouseenter(function(){
var groups, slideIndex, $that = $(this);
slideIndex = $that.index();
groups = theOthers(slideIndex, slidesTotal);
$slides.filter(groups[0]).dosomething();
$slides.filter(groups[1]).dosomethingelse()
})
is there a more simple way to do this with jQuery?
Using .prevAll()
and .nextAll()
you can reduce all of your code in the question down to this:
$('ul > li').mouseenter(function() {
$(this).prevAll().dosomething();
$(this).nextAll().dosomethingelse();
});
.prevAll()
gets all previous siblings, and .nextAll()
gets all following siblings, you can do what you want to each set.
jQuery('someElm ~ .someClass')
matches all elements .someClass
preceded by any siblings seomeElm
精彩评论