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

我已经在网上阅读了所有这些,但其他一切都过于复杂,我只是想实现一个简单的代码,我可以阅读而无需进入子串和所有这些东西,所以我认为这可能是一个很好的挑战作为一个菜鸟在jquery。 我想出了这段代码,但没有成功。

HTML

 

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

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

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

主要是因为你需要知道.each()this是指DOM元素对象,所以要调用它上面的任何jQuery方法,你需要将它传递给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 }); 

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

编辑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 } }); 

对于一个简短但难以理解的代码(这也是未经测试的,顺便说一句),这是怎么回事?

如果有人在徘徊,我想出了以下function。 非常感谢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'); } }); }); 

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