优化jquery prev选择器

时间:2012-08-07 14:41:49

标签: jquery jquery-selectors

有没有办法让下面的选择器更好?
没有添加额外的类或id? 只选择从item-2向下计算的第一个item-5 这有效,但必须有一种更简单的方法。

$first_previous = $($('li.item-5').prevAll('.item-2')[0]);

<ul>
   <li class="item-1">list item 1</li>
   <li class="item-2">Unkown number of item-2 will happen</li>
   <li class="item-2">Unkown number of item-2 will happen</li>
   <li class="item-2">list item 2 Only select this one, not the other #2</li>
   <li class="item-3">list item 3</li>
   <li class="item-4">list item 4</li>
   <li class="item-5">list item 5 Start here</li>
   <li class="item-2">it might even occur after the item-5</li>
</ul>

1 个答案:

答案 0 :(得分:2)

你可以尝试:

$(this).siblings('.item-2').eq(1);

(其中$(this)是一个包含类.item-5的元素的jQuery对象)

但是你会想要使用类似http://jsperf.com/的东西来找出哪种方式更快!

Working example here

更新

然后试试这个:

$(this).siblings('.item-2').last();

.last()的文档

好的......然后试试:

$(this).prev('.item-2')

用途.prev()

更新2

循环项目并获得第一个你想要的项目:

$('.item-5').prevAll().each(function() {
    if ($(this).hasClass('item-2')) {
        alert($(this).text());
        return false; // break early
    }
});​

Example here