开发者

Help with refactoring jQuery menu

    $('#menu > li').hover(function() {
        $(this).prev().addClass('nobg');
    }, function() {
        $(this).prev().removeClass('nobg');
    });
    $('#menu > li:has(.submenu)').hover(function() {
        $(this).ad开发者_如何学运维dClass('active').children('ul').show();
        $(this).prev().addClass('nobg');
    }, function() {
        $(this).removeClass('active').children('ul').hide();    
        $(this).prev().removeClass('nobg');
    });

.. works great but looks really ugly, is it possible to compress this in fewer lines?

Many thanks for your help.


I doubt this can't be done with just CSS... but...

"hover" has an overload that only takes one function, which will be called for both events. Also, you can use toggleClass instead of add and remove.

$('#menu > li').hover(function() {
    $(this).prev().toggleClass('nobg');
});

$('#menu > li:has(.submenu)').hover(function() {
    $(this).toggleClass('active').children('ul').toggle();
    $(this).prev().toggleClass('nobg');
});

The above code probably wont work though, because you'll be calling the toggles twice for anything with a submenu... I would try it with the code below. Posting a jsfiddle with your current trial would be extremely helpful. I could verify that it works for your case :) Or just post the html.

$(('#menu > li').hover(function() {
    $(this).toggleClass('active').children('ul').toggle();
    $(this).prev().toggleClass('nobg');
});

In addition, couldn't your css determine the visibility of the child uls?

.active>ul
{
    display:list-item;
}

If so, you can get ride of ".children('ul').toggle()" all together.


Maybe:

$('#menu > li').hover(function () {
    $(this).prev().stop(true, true).toggleClass('nobg');
});
$('#menu > li:has(.submenu)').hover(function() {
    $(this).toggleClass("active")
        .children('ul').stop(true, true).toggle();
});

Based on http://api.jquery.com/hover/ (last example).

The use of "stop" is to avoid problems like here http://forum.jquery.com/topic/hover-and-toggleclass-fail-at-speed

Leave me a comment if it doesn't work.


Adding onto @xixonia's solution, you could split out the functions into separate functions like this code below (untested):

var nobgtoggle = function() { $(this).prev().toggleClass('nobg'); }
var submenutoggle = function() {
    $(this).toggleClass('active').children('ul').toggle();
    nobgtoggle();
};

$('#menu > li').hover(nobgtoggle);
$('#menu > li:has(.submenu)').hover(submenutoggle);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜