You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用jQuery仅定位.haccordion容器下的顶级标题?

解决方案:仅选中.haccordion的顶级标题

你的问题出在选择器的层级逻辑上:原来的$(".haccordion :header")使用了后代选择器(空格),会匹配.haccordion容器下所有层级的标题元素。要只选中顶级(直接子元素)的标题,你需要改用直接子选择器(>):

修改后的jQuery代码:

$(document).ready(function(){
  $(".haccordion > :header").css("background-color","yellow");
});

原理说明

  • $(".haccordion > :header") 中的>表示仅匹配.haccordion的直接子元素里的标题(h1-h6),不会选中嵌套在子容器(比如.section、section)里的标题。
  • 对应你的HTML结构,这个选择器会精准选中:
    • <h2>Target this</h2>
    • 第一个<h3>Target this</h3>
    • 第三个<h3>Target this</h3>
  • 嵌套在子容器内的<h3>Don't target this</h3>和<h4>Don't target this</h4>会被自动排除。

你也可以用jQuery的.children()方法实现完全相同的效果,代码如下:

$(document).ready(function(){
  $(".haccordion").children(":header").css("background-color","yellow");
});

.children()方法默认只获取当前元素的直接子元素,和直接子选择器的作用逻辑一致。

内容的提问来源于stack exchange,提问作者DeanH

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 11:39:50