1

I'm trying to bind both a mouseenter and a mouseleave event to each <li> within a container, but both events share a few common variables I'd like to share between the 2 events.

I know it would be very simple to do something like this:

$( '.nav li' )
    .on( 'mouseenter', function()
    {
        var $children   = $( this ).find( '.children' ),
            h           = $children.children().outerHeight(),
            speed       = 250;
        $children
            .stop().clearQueue()
            .animate({ height: h }, speed );
    })
    .on( 'mouseleave', function()
    {
        var $children   = $( this ).find( '.children' ),
            h           = $children.children().outerHeight(),
            speed       = 250;
        $children
            .stop().clearQueue()
            .animate({ height: 0 }, speed );
    });

But what sort of performance hinderances would be involved in storing variables within the scope of the "each" function? (To avoid copying and pasting variables in both bind)

$( '.nav li' ).each( function()
{
    var $children   = $( this ).find( '.children' ),
        h           = $children.children().outerHeight(),
        speed       = 250;

    $( this )
        .on( 'mouseenter', function()
        {
            $children
                .stop().clearQueue()
                .animate({ height: h }, speed );
        })
        .on( 'mouseleave', function()
        {
            $children
                .stop().clearQueue()
                .animate({ height: 0 }, speed );
        });
});

The reason I am not using something like (function(){})() is because each list item has it's own children.

So what are the performance differences?

4

1 に答える 1

0

私は混乱していますが、両方とも同じように見えるので、両方を同じ呼び出しでバインドしてみませんか。

.bind('mouseenter mouseleave', function(event){
  var $children   = $( this ).find( '.children' ),
    h           = event.type == "mouseenter" ? $children.children().outerHeight() : 0,
    speed       = 250;
        $children
            .stop().clearQueue()
            .animate({ height: h }, speed );

 })
于 2013-02-26T20:10:39.610 に答える