本文介绍了jQuery:prev(< selector>)不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在jQuery中使用prev()时遇到麻烦,因为它没有选择正确的元素.

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

我的HTML结构如下:

My HTML structure is as follows:

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

活动"部分是#contact.我想选择跳过<hr>

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

active = active.prev('section')似乎不起作用.我想我可能看错了文档...

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

如果我拿出<hr>,一切都会很好.关于如何跳过prev()上的<hr>的任何想法?

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

TIA

推荐答案

.prev() API文档给出了以下描述:

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

所以,问题在于hr在那并且正在被.prev()搜索,然后针对'section'选择器进行了测试.

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

您可以调用一次.prev()跳过该hr,然后在该部分再次调用它:

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

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

或使用.prevAll()并找到最接近的前一个(以防万一之前还有其他节):

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

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

这篇关于jQuery:prev(&lt; selector&gt;)不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!