2015-02-11 31 views
0

我的问题是2倍。我有以下代码:问题与组内循环jQuery选择器

$photosContainer = $("#photos-fs") 
$photos = $photosContainer.find(".photo"); 
$length = $photos.length; 

if ($length > 1) { 
    setTimeout(showNextPhoto, 3000); 
} 

function showNextPhoto() { 

    //$current = $photos.eq(0); <-- this works 
    //$next = $photos.eq(1); <-- this works 

    $current = $photos.find(".current"); <-- this does not 
    $next = $current.next(); <-- this does not 

    //do stuff with the selected elements here 
} 

什么,我想实现基本上是找一个容器内和.current归类元素的下一个兄弟(或第一组,如果当前是最后一个),然后动画他们通过添加css类。问题是,虽然我可以通过.eq(0)和.eq(1)获得元素,但在使用类(.current)或next()函数时,它们不会被选择为“正确”。如果我控制台登录对象,我得到适当的对象,但?

我一直使用find(“。blahblah”)方法在组中的分类元素之间导航,所以不确定它为什么不在这里工作?虽然可能是愚蠢的东西?

以供参考,这是HTML结构:

<div id="photos-fs"> 
    <div class="photo current" style="background-image: url(images/fs-image-01.jpg);"></div> 
    <div class="photo" style="background-image: url(images/fs-image-02.jpg);"></div> 
</div> 

此外,有没有一个很好的前瞻性和优雅的方式来测试的最后一个项目,因此,如果当前项目是最后一个(也许。去年? )你能和我一起分享一下吗?

干杯!

+0

您的“.current”应该从图片切换到图片不是吗? “.current”仅适用于可见的人,对吗? – Julo0sS 2015-02-11 10:22:38

+0

这是正确的:) – geodeath 2015-02-11 10:24:48

+0

它是用.filter解决还是不解决? .find应该工作太... http://api.jquery.com/find/ – Julo0sS 2015-02-11 10:30:27

回答

0

在声明中,您需要使用.filter()而不是.find()。使用替代

$photos.filter(".current"); 

$photos.find(".current"); 

来测试的最后一个项目,因此,如果当前项目是最后一个

您可以使用.is()

yourElement.is(':last') 
+1

梦幻般,工作得很好......我怎么会忘记过滤器?愚蠢的我!非常感谢! – geodeath 2015-02-11 10:26:48