2016-01-06 53 views
1

我有一个包含其他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代码片段

+0

'$( 'P.Q') .last()'? – roullie

+0

呃,没有'最后'。这些都在同一个家长吗? – Taplar

+0

是的,他们都在一个父母的div呼叫消息和P与类Q是第二人,而正常的P是第一人 –

回答

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>

相关问题