I have a set of span elements as below
<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>
I have attached mouse in a开发者_JS百科nd mouse out events to each of the span elements. Now, on mouse in event is it possible to find out using jQuery whether the current hovered span element is the first span element with the class foo?
You might want to check it's .index()
$('.foo').bind('mouseover', function(){
alert('I am ' + $(this).index());
});
If you explicitly need to only check for the first-child
, use the selector :first-child
.
$('.foo').bind('mouseover', function(){
if($(this).is(':first-child'))
alert('I am first');
});
Try it here: http://www.jsfiddle.net/YjC6y/5/
Reference.: .index(), .is(), :first-child
Like this:
if($(this).is(':first-child'))
Like so:
if($(this).is(":first-child")){
}
All the answers provided here are correct. However, for a more general rule, you can use the :eq()
selector:
$('.foo').bind('mouseover', function(){
if($(this).is(':eq(0)')) {
alert('I am first');
}
});
(adapting jAndy's answer)
This tests that the element is at the 0th index among its siblings (i.e. is first -- eq
uses zero-based indexing). You could check for the third item with
if ($(this).is(':eq(2)')) {
精彩评论