jQuery Navigation添加活动类

时间:2014-06-01 23:03:59

标签: javascript jquery

不知何故,我的代码在添加活动类时遇到了问题。如果选择的第一个菜单比添加到<nav>,自身<li>以及活动类的下一个<li>

<nav id="cssmenu" class="sidebox_content active">
    <ul class="navmenu">
        <li class="active">
            <a href="Neu-im-Sortiment">Neue Produkte</a>
        </li>
        <li class="has-sub top-cat active"></li>
    </ul>
</nav>

这是我正在使用的Javascript

$(document).ready(function () {

    var url = window.location;
    // Will only work if string in href matches with location
    $('ul.navmenu a[href="' + url + '"]').parent().addClass('active');

    // Will also work for relative and absolute hrefs
    $('ul.navmenu a').filter(function () {
        return this.href == url;
    }).parent().addClass('active').parent().parent().addClass('active');
});

如果单击第二个列表,则所有内容都像魅力一样。 .partent()错了吗?

1 个答案:

答案 0 :(得分:2)

我假设以下内容:

我怀疑主要问题是window.location是一个对象,而不是一个字符串。对于这篇文章的网址,它看起来像这样:

window.location = {
    "ancestorOrigins": {
        "length": 0
    },
    "origin": "http://stackoverflow.com",
    "hash": "",
    "search": "",
    "pathname": "/questions/23985401/jquery-navigation-add-active-class",
    "port": "",
    "hostname": "stackoverflow.com",
    "host": "stackoverflow.com",
    "protocol": "http:",
    "href": "http://stackoverflow.com/questions/23985401/jquery-navigation-add-active-class"
};

您可以使用window.location.href,但完整的网址可能不适合您的用途。请改为window.location.pathname

$(document).ready(function () {
    "use strict";
    var path = window.location.pathname, // skip the domain and truncate any hashtag nonsense and/or url parameters 
        link = $('ul.navmenu a').filter(function (i) {
            var startOfPath = path.indexOf(this.href) === 1, // pathname starts with a slash
                anywhereInPath = path.indexOf(this.href) > -1,
                endOfPath = path.indexOf(this.href) === path.length - this.href.length;
            return startOfPath || anywhereInPath || endOfPath; // anywhereInPath is most likely to be true
        }),
        li = link.parents('li'), // to get the LI element, or you could do link.parent(), since the LI is the immediate ancestor
        nav = link.parents('nav'); // to get the NAV element, or you could do li.parents('nav'), or you could do li.parent().parent() (etc.)
        li.addClass('active'); // add class to LI
        nav.addClass('active'); // add class to NAV
        // or you could do both with the same call:
        //  $(li, nav).addClass('active');
});

压缩语法(将其全部链接):

$(document).ready(function () {
    "use strict";
    var path = window.location.pathname;
    $('ul.navmenu a').filter(function (i) { // this selects all A elements that have an ancestor UL with class "navmenu"
        var existsInPath = yourLogic(); // and returns only those that match this criteria
        return existsInPath;
    }).parents('li').addClass('active').parents('nav').addClass('active');
});