2010-10-12 80 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)')) {