使用JQuery,你如何檢查一個元素的前一個兄弟是否是第一個孩子?JQuery:檢查前一個兄弟是否是第一個孩子
我曾嘗試下面的代碼,但它不工作:
if($(this).prev() === $(this).siblings(":first-child")){
//do something
}
使用上述===
方法的一個例子:http://jsfiddle.net/xnHfM/
使用JQuery,你如何檢查一個元素的前一個兄弟是否是第一個孩子?JQuery:檢查前一個兄弟是否是第一個孩子
我曾嘗試下面的代碼,但它不工作:
if($(this).prev() === $(this).siblings(":first-child")){
//do something
}
使用上述===
方法的一個例子:http://jsfiddle.net/xnHfM/
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
}
附:我會嘗試看看這個解決方案。是VS( ':第一個孩子')的PERF =>http://jsperf.com/jquery-check-previous-first-child
編輯:看最後的評論,謝謝@RightSaidFred :)
+1 - 謝謝你,一個聰明的解決方案,但不像Yoshi的 – 2011-12-14 14:31:37
這不會是最有效的方式,但你可以使用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>
$(this).parent().find(">:first-child")[0] == $(this).prev()[0]
嘗試這個:
if ($(this).prev(':first-child').length > 0) {
你問這個元素是否是第二個孩子?將$(this).prev()。prev()。length == 0`工作還是你的意思是別的? – wrschneider 2011-12-14 14:27:52