使用 jQuery 在导航菜单中突出显示当前页面项目

发布于 12-27 21:01 字数 1056 浏览 2 评论 0原文

我已经在网上阅读了所有有关此内容的内容,但其他所有内容都过于复杂,我只想实现一个简单的代码,我可以阅读它而无需进入子字符串和所有其他内容,所以我认为这对于菜鸟来说可能是一个很好的挑战在 jquery.我已经想出了这段代码,但没有成功。

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');
        }
    })
})

希望大家不要喷我,我的目的纯粹是学术性的,而不是得到结果。这里有什么问题呢?我没有收到任何错误日志或任何其他内容。

编辑:删除了结尾的斜杠(感谢贾斯汀),也尝试了 Phrogz 的建议,但没有运气。如果有人愿意接受挑战,该网站位于@egegorgulu.com

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: 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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

终难遇2025-01-03 21:01:24

在您的 js 中,您的路径后面附加了一个尾部斜杠,但标签的 href 中没有尾部斜杠。因此,除非您的服务器添加尾部斜杠,否则这些路径将永远不会匹配。

In your js you have a trailing slash appended to the path but no trailing slash in the href of your tags. So unless your server adds a trailing slash these paths would never match.

贱人配狗天长地久2025-01-03 21:01:24

我可以发现你的 JavaScript 中有一些错误。

主要是因为您需要知道在 .each() 中,this 引用了 DOM 元素对象,因此要调用其上的任何 jQuery 方法,您需要传递 this 到 jQuery 函数:$(this)

因此,请尝试以下操作:

$(document).ready ( function(){
    var path = window.location.pathname;
    $('#nav li a').each(function() {
        if( path === "/"+this.id ){ // EDIT: This was the problem with the if
            $(this).addClass('active'); // "this" is a DOM element, not a jQuery object
        } else {
            $('#home').addClass('active'); // you missed the $
        }
    }); // always get in the habit of being explicit with your semicolons
});

编辑: if 的问题是您使用了赋值运算符 = 而不是比较运算符 == (类型转换相等)/ === (相同类型相等)。我已经编辑了上面的代码来解决这个问题。

编辑 2:好的,让我们尝试一种新方法,利用 jQuery 的 filter() 函数来利用 上的 href 属性> 元素来查找匹配:

$(document).ready ( function(){
    var path = window.location.pathname;
    var $navLinks = $('#nav li a');
    $navLinks.removeClass('active'); // start with a blank slate
    $navLinks.filter(function() {
        return path.indexOf(this.href) === 0; // test if the pathname starts with the current link's href attribute
    }).addClass('active'); // find a matching link to add the class to where the href attribute starts with the pathname
    if ($navLinks.filter('.active').length === 0) { // if nothing matches
        $('#home').addClass('active'); // make the home link active as a default
    }
});

作为学术的一边,请注意,如果您愿意,您可以利用 jQuery 强大的链接语法和一些 JS 知识来进一步压缩它,这样它就可以变得像这样小:

$(document).ready ( function(){
    if (!$('#nav li a').removeClass('active').filter(function() {
            return window.location.pathname.indexOf(this.href) === 0;
        }).addClass('active').end().filter('.active').length) {
        $('#home').addClass('active'); // make the home link active as a default
    }
});

How's that for a简短但难以理解的代码(也未经测试,顺便说一句)?

There is a few mistakes in your Javascript that I can spot.

Primarily because you need to know that within .each(), this refers to the DOM element object, so to call any jQuery methods on it, you need to pass this to the jQuery function: $(this).

So try the following instead:

$(document).ready ( function(){
    var path = window.location.pathname;
    $('#nav li a').each(function() {
        if( path === "/"+this.id ){ // EDIT: This was the problem with the if
            $(this).addClass('active'); // "this" is a DOM element, not a jQuery object
        } else {
            $('#home').addClass('active'); // you missed the $
        }
    }); // always get in the habit of being explicit with your semicolons
});

EDIT: The problem with your if was that you used the assignment operator = instead of the comparison operator == (equality with type conversion) / === (equality with same types). I have edited the code above to address that.

EDIT 2: Okay, let's try a new approach that leverages jQuery's filter() function to make use of the href attribute on the <a> elements to find a match:

$(document).ready ( function(){
    var path = window.location.pathname;
    var $navLinks = $('#nav li a');
    $navLinks.removeClass('active'); // start with a blank slate
    $navLinks.filter(function() {
        return path.indexOf(this.href) === 0; // test if the pathname starts with the current link's href attribute
    }).addClass('active'); // find a matching link to add the class to where the href attribute starts with the pathname
    if ($navLinks.filter('.active').length === 0) { // if nothing matches
        $('#home').addClass('active'); // make the home link active as a default
    }
});

As an academic aside, note that you can make use of jQuery's powerful chaining syntax and some JS knowledge to compress this even more if you like, so that it could become as small as:

$(document).ready ( function(){
    if (!$('#nav li a').removeClass('active').filter(function() {
            return window.location.pathname.indexOf(this.href) === 0;
        }).addClass('active').end().filter('.active').length) {
        $('#home').addClass('active'); // make the home link active as a default
    }
});

How's that for a short but hard-to-understand bit of code (which is also untested, btw)?

一百个冬季2025-01-03 21:01:24

如果有人徘徊,我为此想出了以下功能。非常感谢GregL的指点,对我帮助很大。

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'); 
        }
    }); 
});

无冲突的原因是因为我在联系页面上使用了嵌入式联系表单。我很确定第二个 if 是不必要的,但一旦我让它正常工作就不想删除它。

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'); 
        }
    }); 
});

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文