19

I'm having trouble using prev() in jQuery where it's not selecting the right element.

My HTML structure is as follows:

<section id="about">
    ...
</section>
<hr>
<section id="contact">
    ...
</section>

The "active" section is #contact. I want to select the previous section skipping over the <hr>

active = active.prev('section') doesn't seem to be working. I think I may be reading the docs wrong...

If I take out the <hr> everything works beautifully. Any ideas on how to skip the <hr> on prev()?

TIA

4

4 回答 4

28

I think I may be reading the docs wrong...

The API docs for .prev() give this description:

Description: Get the immediately preceding sibling of each element in the set of matched elements, optionally filtered by a selector.

So, the problem is that the hr is there and being searched by .prev(), then tested against the 'section' selector.


Any ideas on how to skip the <hr> on prev()?

You could call .prev() once to skip over that hr then call it again for the section:

active = active.prev().prev('section');

Or use .prevAll() and find the closest-preceding one (in case there are any other sections occurring before it):

active = active.prevAll('section').first();
于 2011-03-27T22:29:50.940 回答
7

Use prevAll() instead

active = active.prevAll('section').first();

from jQuery documentation:

prev() => "Get the immediately preceding sibling" so it will only get the first element.

prevAll() => "Get all preceding siblings of each element in the set of matched elements, optionally filtered by a selector."

That's why when you remove the <hr>, it will work with prev().

于 2011-03-27T22:30:35.433 回答
1

Or try:

<section id="about">
    ...
<hr>
</section>
<section id="contact">
    ...
</section>
于 2011-03-27T22:31:30.447 回答
1

做就是了

active = active.prevAll('section').eq(0);

似乎 .prev() 和 .next() 只选择最近的兄弟,无论您是否为其提供特定的选择器。如果该选择器与同级不匹配,.next('section').length 将为 0。因此,通过使用上述方法,您可以获得与您的选择器匹配的所有先前同级,并使用 .eq(0) 选择最接近的一个.

于 2019-09-28T23:01:29.623 回答