如何使用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
相关产品推荐
相关产品推荐

