找到没有特定单词的下一个对象

时间:2014-05-08 17:20:42

标签: jquery next

我的html中有这些div:

<div class="slide" style=""></div>
<div class="slide" style="background: url(/img/2.jpg)"></div>
<div class="slide" style="background: url(/img/3.jpg)"></div>
<div class="slide" style="background: url(/img/4.jpg)"></div>
<div class="slide" style=""></div>
<div class="slide" style=""></div>
<div class="slide" style=""></div>

我有一个var,它是上面一个div的索引, 让我们说它等于2,所以它是以3.jpg为背景的那个。

现在,我正在尝试使用类“slide”获取下一个div的索引,该索引大于我的var并且在“style”中没有“background”。 如果没有像索引大于我的var那样的div,我想从列表的开头搜索div。

同样地,我试图在我的var之前找到最后一个div,在“styles”中没有单词“background”,同样地,如果没有这样的div,我想从结尾处开始搜索名单。

所以基本上我正在尝试为nextDiv获取4的值,并为lastDiv获取0,对于上面的示例。

我知道$.nextAll():first有助于实现我的需要,而且我也知道,在线型“样式”中选择'.slide'没有“背景”可以使用$(".slide [style*='background']")完成,但我找不到将语法放在一起添加所需条件的方法。

请帮忙。 谢谢。

1 个答案:

答案 0 :(得分:1)

  

我有一个var,它是上面一个div的索引,假设它等于2,所以它是以3.jpg为背景的那个。

     

...

     

现在,我试图用类&#34; slide&#34;来获取下一个div的索引,哪个索引大于我的var,哪个没有&#34;背景&#34; in&#34; style&#34;。

文字要求所需要的是eqnextAllfilter的组合,以及(如果您真的想要索引){{ 3}}

var index = $(".slide").eq(startingIndex).nextAll(".slide").filter(function() {
    return $(this).attr("style").indexOf("background") === -1;
}).index();

这将为您提供相对于其兄弟姐妹(所有这些)的元素索引。

但如果您只想要该元素,请改用index

var nextSlideWithoutBackground = $(".slide").eq(startingIndex).nextAll(".slide").filter(function() {
    return $(this).attr("style").indexOf("background") === -1;
}).first();

实际上,你可以使用first,但它是一个伪选择器,所以它可能不比使用nextAll更好。不过,这就是它的样子:

var index = $(".slide:gt(" + startingIndex + ")").filter/*...and so on...*/
相关问题