如何根据开放链接应用类?

时间:2016-05-15 10:20:09

标签: javascript php jquery

我的侧边栏菜单可以展开和显示部分的子部分,如下所示。 open 部分包含open active类,点击的链接包含active类。

我的所有链接都有不同的#url。所以这将确定类。

如何根据打开的链接自动放置open activeactive类?我也可以使用PHP。

<ul class="menu-items scroll-content">
<li class="open active">
    <a href="javascript:;"><span class="title">first section</span>
<span class="open arrow"></span></a>
<span class="icon-thumbnail">LV</span>
    <ul class="sub-menu">
        <li class="active">
            <a href="page.php#first1">First Section 1</a>
            <span class="icon-thumbnail">au</span>
        </li>
        <li class="">
            <a href="page.php#first2">First Section 2</a>
            <span class="icon-thumbnail">ou</span>
        </li>
    </ul>
</li>
<li class="">
    <a href="javascript:;"><span class="title">Second section</span>
<span class="arrow"></span></a>
<span class="icon-thumbnail">LV</span>
    <ul class="sub-menu">
        <li class="">
            <a href="secondpage.php#second1">Second Section 1</a>
            <span class="icon-thumbnail">au</span>
        </li>
    </ul>
</li>
</ul>

1 个答案:

答案 0 :(得分:0)

试试这样:

HTML:

<ul>
    <li class="">
            <a href="javascript:;"><span class="title">first section</span>
            <ul class="sub-menu">
                    <li class="">
                            <a href="page.php#first1">First Section 1</a>
                            <span class="icon-thumbnail">au</span>
                    </li>
                    <li class="">
                            <a href="page.php#first2">First Section 2</a>
                            <span class="icon-thumbnail">ou</span>
                    </li>
            </ul>
    </li>
    <li class="">
            <a href="javascript:;"><span class="title">Second section</span>
            <ul class="sub-menu">
                    <li class="">
                            <a href="secondpage.php#second1">Second Section 1</a>
                            <span class="icon-thumbnail">au</span>
                    </li>
            </ul>
    </li>
</ul>

JS:

var href = location.pathname+location.hash;

$('.sub-menu > li > a').each(function() {
    if ($(this).attr("href") == href) {
            $(this).parent('li').addClass('active');
            $(this).parent().parent().parent('li').addClass('open active');
    }
});