jquery - 针对相同的 child ,但只针对某些不同的 parent ——CSS 和 jQuery 选择器样式

标签 jquery css jquery-selectors css-selectors

有没有一种方法可以只定位选定父项的某些子项,而不会复制子项选择器并使选择器的长度超出图表?

比如我想选中某个div的first-child paragraph

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>不想成为目标。

我的问题是:我能知道如何声明 child 并将其添加到所有 parent 的前面吗?像这样的东西:

.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

最佳答案

在 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')

关于jquery - 针对相同的 child ,但只针对某些不同的 parent ——CSS 和 jQuery 选择器样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11783703/

相关文章:

jquery - 使用 jQuery 查找选定控件或文本框的标签

javascript - 使用 jquery 存储值并在其他地方使用它

css - 底部的页脚 - 100% 高度

jquery 选择 Table,但只能在 Div 之后

javascript - 用于添加类宽度的 js 代码不起作用

css - 在 IE8 中,如何在没有任何重叠的情况下使用 Telerik 网格和 YUI3 网格?

JavaScript - 检查这个(当前元素)是否有一个以结尾的类

javascript - Jquery/CSS 菜单 - 延迟切换直到上一个切换完成

javascript - 不在桌面版时隐藏 Logo

jquery - 检查特定的父选择器是否存在