使用jQuery突出显示导航菜单中的当前页面项目 [英] Highlighting current page item in the nav menu with jQuery

查看:137
本文介绍了使用jQuery突出显示导航菜单中的当前页面项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在线阅读了所有相关内容,但其他所有内容都过于复杂,我只想实现一个简单的代码即可读取,而无需进入子字符串和所有其他内容,因此我认为这可能是一个不错的挑战作为jquery的菜鸟.我已经提出了这段代码,但是没有成功.

I've read all about this online but everything else was just overly complicated and I just want to implement a simple code that I can read without going into substrings and all that stuff, so i thought this might be a good challenge for as a noob in jquery. I've come up with this code but without success.

HTML

<ul id="nav">
    <li><a href="/" id="home" class="lettering">HOME</a></li>
    <li><a href="/about" id="about" class="lettering">ABOUT</a></li>
    <li><a href="/works" id="works" class="lettering">WORKS</a></li>
    <li><a href="/contact" id="contact" class="lettering">CONTACT</a></li>
</ul>

jQuery

$(document).ready ( function(){
    var path = window.location.pathname;
    $('#nav li a').each(function() {
        if( path = ("/"+this.id+"/") ){
            this.addClass('active');
        } else {
            ('#home').addClass('active');
        }
    })
})

我希望你们不要解雇我,我的意图纯粹是学术性的,而不是取得成果.这里有什么问题?我没有收到任何错误日志或其他任何内容.

I hope you guys don't flame me, my intentions are purely academic rather than getting results. What is the problem here? I'm not getting any error logs or anything btw.

edit:删除了斜杠(感谢Justin),也尝试了Phrogz的建议,但没有运气.如果有人愿意接受挑战,请访问该网站@ egegorgulu.com

edit: removed the trailing slashes(thanks Justin), also tried what Phrogz suggested but no luck. If anyone feels up to the challenge, the site is located @ egegorgulu.com

推荐答案

如果有人在流浪,我想出了以下函数.非常感谢GregL的指导,这对我有很大帮助.

If anybody is wandering, I came up with the following function for this. Many thanks to GregL for his pointers, it helped me a lot.

jQuery.noConflict()( function(){
    var $ = jQuery;
    var path = window.location.pathname;
    $('#nav li a').each(function() {
        if( path === "/" + this.id + "/" ){ 
            $(this).addClass('active'); 
        } else if( path === "/" ) {
            $('#home').addClass('active'); 
        }
    }); 
});

出现noConflict的原因是因为我在联系页面上使用的是嵌入式联系表.而且我很确定第二个if是不必要的,但是一旦我正常工作就不想删除它.

The reason for the noConflict is because I'm using an embedded contact form on my contact page. And I'm pretty sure that the second if is unnecessary but didn't want to remove it once I got it working properly.

这篇关于使用jQuery突出显示导航菜单中的当前页面项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆