jQuery: prev() not working?

2019-01-19 10:41发布

问题:

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

回答1:

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();


回答2:

Use prevAll() instead

active = active.prevAll('section')

from jQuery documentation:

prev() => "Get the immediately preceding sibling" so it will only get the first element, that's why when you remove the <hr>, it will work.



回答3:

Or try:

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