针对相同的孩子,但只有某些不同的父母 - CSS和jQuery选择器样式

时间:2012-08-02 18:36:03

标签: jquery css jquery-selectors css-selectors

有没有办法只定位选定父母的某些孩子而不重复儿童选择器,并使选择器在长度方面脱离图表?

例如,我想选择某些div的第一个子段落。

CSS就像

.funny > p:first-child, .sad > p:first-child {
 color: red
}

标记

<div class="funny">
  <p>This is red</p>
  <p>This is whatever</p>
  <p>This is whatever</p>
  <p>This is whatever</p>
</div>

<div class="wildcrazy">
  <p>This is whatever</p>
  <p>This is whatever</p>
  <p>This is whatever</p>
  <p>This is whatever</p>
</div>

<div class="sad">
  <p>This is red</p>
  <p>This is whatever</p>
  <p>This is whatever</p>
  <p>This is whatever</p>
</div>

显然,除了有趣和悲伤之外,还有其他许多其他div中的其他第一段也有很多我想要定位的内容,而且还有很多其他div像wildcrazy那样我< em>不想要定位。

我的问题是:我可以告诉孩子如何宣传孩子,并将其与所有父母一同提出来吗?类似的东西:

.funny, .sad, .another_div_class0, .another_div_class1, .another_div_class2, .another_div_class3 > p:first-child

而不是

.funny p:first, .sad p:first-child, .another_div_class0 p:first-child, .another_div_class1 p:first-child, .another_div_class2 p:first-child, .another_div_class3 p:first-child

4 个答案:

答案 0 :(得分:2)

在jquery中:

.funny, .sad, .another_div_class0, .another_div_class1, .another_div_class2, .another_div_class3 > p:first

会转化为:

$('.funny, .sad, .another_div_class0, .another_div_class1, .another_div_class2, .another_div_class3').children('p:first')

答案 1 :(得分:0)

我不知道CSS,但你可以用jquery来做。将所有父类放在选择器中,然后声明如果它是选择器的子项,则只需要p:

$('.funny, .sad, .another_div_class0, .another_div_class1, .another_div_class2, .another_div_class3').each( function() {
    $('p:first-child', this).css(Do whatever you want);
});

答案 2 :(得分:0)

为什么不将另一个类添加到您想要选择的div

<div class="funny selectthis">
  <p>This is red</p>
  <p>This is whatever</p>
  <p>This is whatever</p>
  <p>This is whatever</p>
</div>

<div class="wildcrazy">
  <p>This is whatever</p>
  <p>This is whatever</p>
  <p>This is whatever</p>
  <p>This is whatever</p>
</div>

<div class="sad selectthis">
  <p>This is red</p>
  <p>This is whatever</p>
  <p>This is whatever</p>
  <p>This is whatever</p>
</div>

然后使用此

$('.selectthis').find('p:first').css('color','red');​

http://jsfiddle.net/U6qhb/

答案 3 :(得分:0)

$('.funny, .sad, .another_div_class0, .another_div_class1, .another_div_class2, .another_div_class3').find('p:first')
相关问题