边栏按 URL 选择当前菜单标题



我想通过当前网址突出显示相关的菜单项。

这是 HTML

       <ul class="nav">
          <li>
            <a href="/ratings">Rate</a>
          </li>
          <li class="">
            <a href="/ratings/list">All Pics</a>
          </li>
          <li>
            <a href="/ratings/new">Upload Your Own</a>
          </li>
        </ul>

和简单的jquery:

$(function () {
    var active = 'active',
        $lastMatch,
        s = window.location.pathname;
    $('.nav a').each(function (index, item) {
        if (s.indexOf($(this).attr("href")) !== -1) {
            $lastMatch = $(this).closest('li');
        }
    });
    if ($lastMatch.length){
        $lastMatch.addClass(active);
    }
});

工程。但是,如果我导航到与`0.0.0.0:3000/ratings/list不同的网址0.0.0.0:3000/ratings/list/1,则会发生一个奇怪的错误,并且它确实保持"活动"。

尝试使用火虫进行调试,我看到 li 得到了active类,但它被其他东西抵消了,我不知道它是什么。

尝试更改以下行:

if (s.indexOf($(this).attr("href")) !== -1) {

对于这个:

if (s.indexOf($(this).attr("href"), s.length - $(this).attr("href").length) !== -1) {

因此,要比较两个字符串是否在字符串末尾匹配,而不是像您所做的那样在任何部分匹配。这样,您可以避免遇到极端情况。

最新更新