【问题标题】:Home link on the menu does not highlight菜单上的主页链接未突出显示
【发布时间】:2010-03-15 13:57:05
【问题描述】:

我的菜单在单击时会显示活动链接,但主链接 (http://www.obsia.com) 除外。它从不突出显示。 我试着到处玩,但我似乎无法弄清楚。这是我用来突出显示链接的 jquery 代码?

 $(function(){
   var path = location.pathname.substring(1);
   if ( path )
     $('.nav a[href$="' + path + '"]').attr('class', 'active');   
 });

我在products pages 上还有另一个菜单,我想在全局菜单上突出显示兄弟姐妹的父母和我们的产品。这是产品菜单的 jquery 代码:

 $(function() {
var pathname = location.pathname;
var highlight;
//highlight home
if(pathname == "")
    highlight = $('ul#accordion > li:first > a:first');
else {
    var path = pathname.substring(1);
    if (path)
        highlight = $('ul#accordion a[href$="' + path + '"]');
}highlight.attr('class', 'active');



// hide 2nd, 3rd, ... level menus
$('ul#accordion ul').hide();

// show child menu on click
$('ul#accordion > li > a.product_menu').click(function() {
    //minor improvement
    $(this).siblings('ul').toggle("slow");
    return false;
});

//open to current group (highlighted link) by show all parent ul's
$('a.active').parents('ul').show();
$('a.active').parents('h2 a').css({'color':'#ff8833'});

//if you only have a 2 level deep navigation you could
//use this instead
//$('a.selected').parents("ul").eq(0).show();

}); });

我尝试添加这个:

        $(this).parents('ul').addClass('active');

但这似乎不起作用?

有没有人有一个简单的方法来完成它? 任何帮助将不胜感激。

亲切的问候, G

【问题讨论】:

    标签: menu highlighting breadcrumbs


    【解决方案1】:

    我调试了你的 Javascript。主页链接没有突出显示,因为对于主页,location.pathname 被评估为字符串“/”。因此,变量“路径”被分配了空字符串。这意味着变量“highlight”未分配给。

    // path is assigned the empty string
    var path = location.pathname.substring(1);
    
    // evaluating to false
    if (path) {
        // we never get here
        highlight = $('ul#accordion a[href$="' + path + '"]');
    }
    
    // getting a null pointer exception
    highlight.attr('class', 'active');
    

    【讨论】:

    • 感谢 Stephen 成功了——我什至把括号放在第一个 if 语句上 :)
    • 其实刚刚又检查了一遍,即使在主页上使用了更正的代码,我也得到了突出显示未定义的错误?我做错了吗?
    • 嗨,奇怪的循环。我的答案中的代码实际上只是对主页出现错误的原因的解释:-) 这不是问题的解决方案。要修复错误,您的代码需要考虑“路径”是空字符串的情况。
    • 是的,在我写信给你几分钟后,这才有意义。解决了吗:)
    【解决方案2】:

    在 Firebug 中,我在 }highlight.attr('class', 'active'); 行上得到 highlight is undefined 看起来您可能需要更正其上方 If 语句周围的括号?

    【讨论】:

    • 谢谢 Dave .. 我正在努力解决这个问题。那是产品菜单 - 有什么提示为什么全局菜单上的主页链接没有突出显示而其他所有内容都突出显示?
    【解决方案3】:

    我想出了如何让主页链接在菜单栏中突出显示(这是唯一不会在菜单栏中突出显示的链接)。这是我所做的:

     $(function(){
       var pathname = location.pathname;
       var path = pathname.substring(1);
        if(path == "")
            $('.nav a:first').addClass('active');
       else (path)
         $('.nav a[href$="' + path + '"]').attr('class', 'active');   
     });
    

    【讨论】:

      猜你喜欢
      • 2016-11-27
      • 1970-01-01
      • 2016-02-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多