如何选择列表中特定类的每个最后一个子节点

时间:2016-01-06 00:37:20

标签: jquery

我有一个包含其他div列表作为消息的div,我想选择具有相同类的div的每个最后一个子节点。

这是我的代码:

<p>The first paragraph.</p>
<p class="q">The second paragraph.</p>
<p>The third paragraph.</p>
<p class="q">The fourth paragraph.</p>
<p class="q">The fifth paragraph.</p>
<p class="q">The sixth paragraph.</p>
<p>The seventh paragraph.</p>
<p>The seventh paragraph.</p>
<p class="q">The fifth paragraph.</p>
<p class="q">The sixth paragraph.</p>
<p class="q">The sixth paragraph.</p>
<p class="q">The sixth paragraph.</p>

我想要的只是选择班级"q"的每一个孩子。

像这样:

<p>The first paragraph.</p>
<p class="q">The second paragraph.</p> - Selected
<p>The third paragraph.</p>
<p class="q">The fourth paragraph.</p>
<p class="q">The fifth paragraph.</p>
<p class="q">The sixth paragraph.</p> - Selected
<p>The seventh paragraph.</p>
<p>The seventh paragraph.</p>
<p class="q">The fifth paragraph.</p>
<p class="q">The sixth paragraph.</p>
<p class="q">The sixth paragraph.</p>
<p class="q">The sixth paragraph.</p> - Selected

请帮助,无论是否可以通过css,jQuery或PHP代码段完成

1 个答案:

答案 0 :(得分:3)

这很有用。这是两个选择器。

$("p.q + p:not(p.q)").prev("p");
$("p.q:last");

或者单身:

$('p.q + :not(p.q)').prev().add('p.q:last');

可能很复杂,但值得一试:

$(function () {
  $('p.q + :not(p.q)').prev().add('p.q:last').addClass("selected");
});
.selected {background: #ccf;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p>The first paragraph.</p>
<p class="q">The second paragraph.</p>
<p>The third paragraph.</p>
<p class="q">The fourth paragraph.</p>
<p class="q">The fifth paragraph.</p>
<p class="q">The sixth paragraph.</p>
<p>The seventh paragraph.</p>
<p>The seventh paragraph.</p>
<p class="q">The fifth paragraph.</p>
<p class="q">The sixth paragraph.</p>
<p class="q">The sixth paragraph.</p>
<p class="q">The sixth paragraph.</p>