如果其中一个子菜单项处于活动状态,则展开下拉菜单

时间:2012-07-30 13:21:58

标签: javascript jquery html

我有一个下拉菜单,通过点击展开。默认情况下,菜单已折叠。如果其中一个子菜单页面处于活动状态,我希望菜单显示为扩展。我希望这很清楚。这是我的代码。

HTML

<li class="dropdown">
            <a class="disablelink" href="#">Carbohydrates, proteins &amp; fats</a>
            <ul class="sub_navigation">
                <li><a href="carbohydrates.php">Carbohydrates</a></li>
                <li><a href="proteins.php">Proteins</a></li>
                <li><a href="fats.php">Fats</a></li>
            </ul>
        </li>

的jQuery

$(document).ready(function() {
        $('.dropdown').click(function() {
                        // When the event is triggered, grab the current element 'this' and
                        // find it's children '.sub_navigation' and display/hide them
            $(this).find('.sub_navigation').slideToggle(); 
        });

        $(".disablelink").click(function(e) {
            e.preventDefault();
        });

    });

因此,如果用户在carbohydrates.phpproteins.phpfats.php,我希望扩展菜单。我不知道怎么做。有人可以帮忙吗?

1 个答案:

答案 0 :(得分:3)

当页面处于活动状态时,您需要为其链接添加一个额外的类,例如;

<li class="current_page"><a href="carbohydrates.php">Carbohydrates</a></li>

然后,您可以使用jQuery循环浏览菜单,并在任何菜单项具有该类时展开它。

$('.dropdown li').each(function() {
    if ($(this).hasClass('current_page')) {
           $(this).closest('.sub_navigation').slideDown();          
    }            
});

演示:http://jsfiddle.net/R7gkw/

相关问题