Question

I've been aiming to do something simple..but not sure of the best approach. I've ready through jQuery documentation but as this place offers sound advice - I'll punt the question here.

It's basically traversing.

Say I have this minimal code as a simple example (multiple elements on the same page):

<div class='collab'>
<div class='collab_text'>text</div><!--close collab_text-->
</div><!--close_collab-->

<div class='collab'>
<div class='collab_text'>text</div><!--close collab_text-->
</div><!--close_collab-->

In jQuery I simply want to fade collab_text on hover. So I have:

$(".collab").hover(function(){
        $(".collab_text").fadeTo(700, 1.0);
    },function(){
        $(".collab_text").fadeTo(300,0.00001);                          
    });

This will obviously show all the collab_text for all elements when I hover over 1 item. So my question is what is the correct method to get only the hovered collab_text to show. .next() ?, .find() ?

I know my code should be:

$(".collab").hover(function(){
            $(this).XXX(".collab_text").fadeTo(700, 1.0);
        },function(){
            $(this).XXX(".collab_text").fadeTo(300,0.00001);                            
        });

Any information would be greatly appreciated.

Thanks.

Était-ce utile?

La solution

You can use either find, or $() with context

$(this).find(".collab_text").fadeTo(700, 1.0);

or

$('.collab_text', this).fadeTo(700, 1.0);

They are both equal:

Internally, selector context is implemented with the .find() method, so $('span', this) is equivalent to $(this).find('span').

http://api.jquery.com/jQuery/

Autres conseils

In your case I would use children('.collab_text'):

$(".collab").hover(function(){
    $(this).children(".collab_text").fadeTo(700, 1.0);
},function(){
    $(this).children(".collab_text").fadeTo(300,0.00001);                          
});​

Example - http://jsfiddle.net/edjQ7/

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top