1

我正在尝试将 mouseenter 和 mouseleave 事件绑定到<li>容器中的每个事件,但是这两个事件共享一些我想在这两个事件之间共享的公共变量。

我知道做这样的事情会很简单:

$( '.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 );
    });

但是在“每个”函数的范围内存储变量会涉及什么样的性能障碍?(为了避免在两个绑定中复制和粘贴变量)

$( '.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 );
        });
});

我不使用类似的原因(function(){})()是因为每个列表项都有自己的子项。

那么性能差异有哪些呢?

4

1 回答 1

0

I am confused, but why not just bind them both in the same call as it looks identical between both of them.

.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 回答