jQuery :first-child 选择器
封面图
•
2025-09-23
•
jQuery
214
0
0
0
在 jQuery 中,`:first-child` 选择器用于选取**第一个子元素**。它与 CSS 中的 `:first-child` 伪类类似。 --- ### ✅ 基本语法: ```javascript $("selector:first-child") ``` --- ### 🔍 示例说明 假设 HTML 结构如下: ```html <ul> <li>Item 1</li> <li>Item 2</li> <li>Item 3</li> </ul> ``` #### 使用 `:first-child` 选择第一个 `<li>` 元素: ```javascript $("ul li:first-child").css("color", "red"); ``` 这会将 **"Item 1"** 的文字颜色变为红色。 --- ### 📌 注意事项: - `:first-child` 是一个**伪类选择器**,不是 CSS 选择器(虽然和 CSS 一致)。 - 它只匹配**直接子元素中的第一个**,不考虑嵌套结构。 - 如果你想要选**某个父元素下的第一个子元素**,可以这样写: ```javascript $("#parent > :first-child") ``` --- ### 🧠 和 `:first` 的区别: | 选择器 | 含义 | |----------------|----------------------------------| | `:first-child` | 选中**第一个子元素** | | `:first` | 选中**所有匹配元素中的第一个** | 例如: ```html <div class="box">A</div> <div class="box">B</div> <div class="box">C</div> ``` ```javascript $(".box:first-child") // 选中第一个 .box 元素(即 A) $(".box:first") // 同样选中第一个 .box 元素(即 A) ``` 但如果结构是: ```html <div class="box">A</div> <span class="box">B</span> <div class="box">C</div> ``` 那么: ```javascript $(".box:first-child") // 不会选中任何元素,因为 `.box` 不是第一个子元素 $(".box:first") // 选中第一个 `.box` 元素(即 A) ``` --- ### ✅ 总结: - `:first-child` 用于选中某个父元素下的**第一个子元素**。 - 适用于需要精确控制 DOM 结构的场景。 - 注意区分 `:first-child` 和 `:first` 的不同行为。 如需进一步了解其他 jQuery 选择器,欢迎继续提问!
上一篇:
jquery Draggable 拖动效果
下一篇:
jQuery first child of “this”
标题录入,一次不能超过6条
返回顶部
留言
留言
评论