2011-12-14 100 views
2

使用JQuery,你如何检查一个元素的前一个兄弟是否是第一个孩子?JQuery:检查前一个兄弟是否是第一个孩子

我曾尝试下面的代码,但它不工作:

if($(this).prev() === $(this).siblings(":first-child")){ 
    //do something 
} 

使用上述===方法的一个例子:http://jsfiddle.net/xnHfM/

+0

你问这个元素是否是第二个孩子?将$(this).prev()。prev()。length == 0`工作还是你的意思是别的? – wrschneider 2011-12-14 14:27:52

回答

5
if($(this).index() === 1){ // if index is 1 it means it's for sure the second children 
    // here u can grab $(this).prev(), and it's for sure the first one 
} 

演示http://jsfiddle.net/p7sAq/

附:我会尝试看看这个解决方案。是VS( ':第一个孩子')的PERF =>http://jsperf.com/jquery-check-previous-first-child

编辑:看最后的评论,谢谢@RightSaidFred :)

+0

+1 - 谢谢你,一个聪明的解决方案,但不像Yoshi的 – 2011-12-14 14:31:37

1

这不会是最有效的方式,但你可以使用prevAll并计算以前的兄弟姐妹的数量。下面是一个例子(jsFiddle)...

<ul id="test1"> 
    <li>One</li> 
    <li class="two">Two</li> 
</ul> 
<ul id="test1"> 
    <li>One</li>  
    <li>Two</li> 
    <li class="three">Three</li> 
</ul> 
<script> 
alert("Test 1 is..."); 
alert($("#test1 .two").prevAll().length == 1); 
alert("Test 2 is..."); 
alert($("#test2 .three").prevAll().length == 1); 
</script> 
2
$(this).parent().find(">:first-child")[0] == $(this).prev()[0] 
1

尝试这个:

if ($(this).prev(':first-child').length > 0) { 
相关问题