Expand parent menu if child menu is selected

2019-09-18 07:35发布

I have a menu with sub child menus. The problem I am facing is that whenever I select a child menu after page loads, the menu collapses. I want to open the parent menu expanded.

The HTML Code is:


<div id='cssmenu'>
        <ul>
            <li><a href='http://internallink.com/home'><span>Home</span></a></li>
            <li class='active has-sub'><a href='http://internallink.com/products'><span>Products</span></a>
                <ul>
                    <li class='has-sub'><a href='http://internallink.com/product1'><span>Product 1</span></a>
                        <ul>
                            <li><a href='http://internallink.com/subProduct'><span>Sub Product</span></a></li>
                            <li class='last'><a href='http://internallink.com/subProduct'><span>Sub Product</span></a></li>
                        </ul>
                    </li>
                    <li class='has-sub'><a href='http://internallink.com/product2'><span>Product 2</span></a>
                        <ul>
                            <li><a href='http://internallink.com/subProduct'><span>Sub Product</span></a></li>
                            <li class='last'><a href='http://internallink.com/subProduct'><span>Sub Product</span></a></li>
                        </ul>
                    </li>
                </ul>
            </li>
            <li><a href='http://internallink.com/about'><span>About</span></a></li>
            <li class='last'><a href='http://internallink.com/contact'><span>Contact</span></a></li>
        </ul>
    </div>

The JS is:


jQuery(document).ready(function () {
    jQuery('#cssmenu').on("click","li.has-sub .holder",function () {
        var element = jQuery(this).parent('li');
        if (element.hasClass('open')) {
            element.removeClass('open');
            element.find('li').removeClass('open');
            element.find('ul').slideUp();
        }
        else {
            element.addClass('open');
            element.children('ul').slideDown();
            element.siblings('li').children('ul').slideUp();
            element.siblings('li').removeClass('open');
            element.siblings('li').find('li').removeClass('open');
            element.siblings('li').find('ul').slideUp();
        }
    });

    jQuery('#cssmenu ul li.has-sub').prepend('<span class="holder"></span>');

});

How can i expand the parent menu if child menu is selected.

Fiddle: https://jsfiddle.net/x415mjfq/

1条回答
我想做一个坏孩纸
2楼-- · 2019-09-18 08:18

You have the full, absolute URL's in the links; that can be used to your advantage. Simply use document.querySelector with the square bracket selector, and the location.href property:

document.querySelector("a[href='" + location.href + "']").classList.add("selected");

Then, do whatever you need to do to it. In this example, I'm adding the selected class.

Fiddle

查看更多
登录 后发表回答