jQuery在悬停时显示子菜单,如果存在子菜单则添加类

时间:2013-07-09 14:44:59

标签: javascript jquery html

使用jQuery,我希望在菜单li悬停时显示子菜单,以便:当.nav有一个ul.submenu并且.nav li悬停时,显示.submenu并添加类.arrow-down,然后onmouse out隐藏它试。

我的HTML如下:

        <ul class="nav">
            <li><a href="#">Home</a>
            </li>
            <li><a href="#">Facilities</a>
                <ul class="submenu">
                    <li><a href="#">Coaching</a></li>
                    <li><a href="#">Performance Tests</a></li>
                </ul>
            </li>
            <li><a href="#">Trainers</a>
                <ul class="submenu">
                    <li><a href="#">Coaching</a></li>
                    <li><a href="#">Performance Tests</a></li>
                </ul>
            </li>
            <li><a href="#">Membership</a>
                <ul class="submenu">
                    <li><a href="#">Coaching</a></li>
                    <li><a href="#">Performance Tests</a></li>
                </ul>
            </li>
            <li><a href="#">Schedule</a>
                <ul class="submenu">
                    <li><a href="#">Coaching</a></li>
                    <li><a href="#">Performance Tests</a></li>
                </ul>
            </li>
        </ul>

...谢谢

1 个答案:

答案 0 :(得分:3)

$('ul.nav > li').hover(function () {
    if ($(this).find('ul.submenu').length > 0) {
        $(this).find('ul.submenu').show();
        $(this).addClass('arrow-down');
    }
},
function () {
    if ($(this).find('ul.submenu').length > 0) {
        $(this).find('ul.submenu').hide();
        $(this).removeClass('arrow-down');
    }
});