2010-10-12 79 views
2

我有一組跨度元件如以下jQuery和第n個元件

<div> 
    <span class='foo'>foo0</span> 
    <span class='foo'>foo1</span> 
    <span class='foo'>foo2</span> 
    <span class='foo'>foo3</span> 
    <span class='foo'>foo4</span> 
</div> 

我已連接的鼠標和鼠標事件出到每個的跨度元件。現在,鼠標事件是有可能找出使用jQuery目前徘徊span元素是否與類Foo第一span元素?

回答

4

您可能要檢查它的.index()

$('.foo').bind('mouseover', function(){ 
    alert('I am ' + $(this).index()); 
}); 

如果明確只需要檢查的first-child,使用選擇:first-child

$('.foo').bind('mouseover', function(){ 
    if($(this).is(':first-child')) 
     alert('I am first'); 
}); 

嘗試在這裏:http://www.jsfiddle.net/YjC6y/5/

參考:.index().is():first-child

2

像這樣:

if($(this).is(':first-child')) 
+0

但你不檢查wheter類是「福」還是不 – 2010-10-12 12:19:15

+0

@ GOTO:那進入主選擇:)(在其功能使用了' this')。 – BalusC 2010-10-12 12:20:32

+0

@BalusC:哦,你的意思是。是(「:第一個孩子」)的部分檢查與同一類作爲一個主選擇孩子的? – 2010-10-12 12:36:44

0

像這樣:

if($(this).is(":first-child")){ 
} 
0

所有在這裏提供的答案是正確的。然而,對於一個更一般的規則,你可以使用:eq() selector

$('.foo').bind('mouseover', function(){ 
    if($(this).is(':eq(0)')) { 
     alert('I am first'); 
    } 
}); 

(適應jAndy的答案)

這測試該元素是它的兄弟姐妹之間的第0指數(即是第一 - eq使用從零開始的索引)。你可以檢查第三項與

if ($(this).is(':eq(2)')) {