在CSS(IE7 +)或jQuery中是否有一种方法可以选择其first-child具有特定类型的项目,这样就像下面的伪代码一样,您可以选择所有 li 第一个孩子 a :
li:first-child(a)
更新
我一直在寻找@SLaks建议的解决方案,因为我想在一个选择器中获取它。但是.parent()方法更快,请参阅:http://jsfiddle.net/c4urself/Qw8fX/
$("li > a:first-child").parent()
VS
$("li:has(>a:first-child)")
更新2
请参阅jsPerf
中两种方法的性能差异http://jsperf.com/jquery-has-child-vs-parent-child-and-parent
答案 0 :(得分:4)
CSS无法做到这一点,但jQuery可以:
li:has(>a:first-child)
CSS无法做到这一点,因为CSS设计为在浏览器读取HTML时以仅向前的方式应用。始终可以确定哪些CSS规则立即应用于元素 ,而无需等待元素的子元素或后续兄弟元素。
答案 1 :(得分:3)
在jQuery $('ul li a:first-child').parent();
答案 2 :(得分:0)
使用li:first-child伪类,您可以将所需的样式应用于li项,然后设置嵌套在其中的a样式。看看http://reference.sitepoint.com/css/pseudoclass-firstchild
答案 3 :(得分:0)
我不认为它在CSS中是可能的,但在jQuery中你想要使用filter()
。
请确保您根据contents()
而不是children()
进行过滤,因为您需要查看文字节点。
$( function() {
$('li').filter( function() {
return $(this).contents().first().is('a');
}).each( function() {
$('body').append($(this).text() + '<br/>');
});
});
它比在jQuery选择器中执行所有代码需要更多的代码,但性能应该更好。 jQuery选择器在指定单个术语时才真正起作用。