:影响所有孩子的第一个孩子
问题描述:
您好我正在尝试将目标放在.current-cat-parent下的第一个<a>
元素,但是我的jquery代码正在影响下方的所有<a>
元素。我怎样才能瞄准第一个即时<a>
元素?谢谢!:影响所有孩子的第一个孩子
$(".current-cat-parent a:first-child").click(function(e){
e.preventDefault();
if($(this).hasClass('hide')){
$(this).next().slideDown(800);
$(this).removeClass('hide');
} else {
$(this).next().slideUp(800);
$(this).addClass('hide');
}
});
<li class="cat-item cat-item-1 current-cat-parent">
<a title="View all posts filed under Clothing" href="http://site.com/category/clothing">Clothing</a>
<ul class="children">
<li class="cat-item cat-item-3"><a title="View all posts filed under Jeans" href="http://site.com/category/clothing/jeans">Jeans</a></li>
<li class="cat-item cat-item-2 current-cat"><a title="View all posts filed under Suits" href="http://site.com/category/clothing/suits">Suits</a></li>
</ul>
</li>
答
应该
$(".current-cat-parent a:eq(0)").click(function(e){
答
如果您在HTML标记仔细观察,你会发现,所有的a
元素也各自父母的first-child
。该解决方案是使用这些选择之一:
.current-cat-parent > a
.current-cat-parent a:first
.current-cat-parent a:eq(0)
注意:first
和:first-child
是不一样的。
答
取而代之的是:
$(".current-cat-parent a:first-child")
使用直接子>
:
$(".current-cat-parent > a:first-child")
注:
我认为你的主要问题是.hide
CSS类。你为什么需要它?我建议你让它成为一个空白的CSS类或删除它。
锚是所有的第一个孩子在他们的上下文? - >'$(“。current-cat-parent a:first”)' – adeneo