【问题标题】:Find next object without specific word in style查找样式中没有特定单词的下一个对象
【发布时间】:2014-05-08 17:20:42
【问题描述】:

我的 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 作为背景的那个。

现在,我正在尝试使用“幻灯片”类获取下一个 div 的索引,该索引大于我的 var 并且在“样式”中没有“背景”。 如果没有索引大于我的 var 的 div,我想从列表的开头开始搜索 div。

同样,我试图找到我的 var 之前的最后一个 div,“样式”中没有“背景”一词,同样,如果没有这样的 div,我想从末尾开始搜索列表。

所以基本上我试图为 nextDiv 获得 4 的值,为 lastDiv 获得 0 的值,例如上面的示例。

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

请帮忙。 谢谢。

【问题讨论】:

  • 首先删除样式属性中的引号。
  • 对不起,我不小心粘贴了html的片段

标签: jquery next


【解决方案1】:

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

...

现在,我正在尝试使用“幻灯片”类获取下一个 div 的索引,该索引大于我的 var 并且在“样式”中没有“背景”。

literal 要求需要的是 eqnextAllfilter 和(如果你真的想要索引)index 的组合。

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

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

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

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

实际上,您可以使用:gt,但它是一个伪选择器,因此它可能并不比使用nextAll 更好。不过,这就是它的样子:

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

【讨论】:

  • 嗨 T.J.非常感谢您的提示,不幸的是它没有帮助。我找到了一种查找对象的方法:$('.slide').eq(my var).nextAll('.slide:not([style*="background"]):first').index(); 甚至不确定它是否是最好的方法,但它可以工作。
  • @zee:以上工作正常:jsbin.com/cosoyowi/1jsbin.com/cosoyowi/2。也就是说,我真的很生气,因为*= 属性选择器当然是filter - jsbin.com/cosoyowi/3 的更好选择。 :-) 你应该把它作为答案发布并接受它(所以明天某个时候会让你接受它)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-10-11
  • 2010-12-22
  • 1970-01-01
  • 2019-06-19
  • 1970-01-01
  • 2023-03-15
  • 1970-01-01
相关资源
最近更新 更多