根据位置突出显示按钮

我正在尝试根据正在查看的页面突出显示导航按钮(在菜单中)。 这是我到目前为止:

var loca = String(document.location.href); // Get document location and specific page. if (loca) { if(loca.search(RegExp("((/[\w]*)\.php)")) != -1) { activate(loca.match(RegExp("((/[\w]*)\.php)").split("/").join(""))); } else { activate("home"); } } // Activate a button function activate(bName) { $(".button[name=" + bName + "]").css({ "border-left": "1px solid white", "border-right": "1px solid white" }); } 

我想要发生的是:

  1. 获取页面的URL
  2. 获取页面的特定文件名,如果没有找到,那么我们就在主页上。
  3. 使用jQuery,我尝试找到按钮的名称,如果名称与文件名匹配,则突出显示它。

事实是,这只突出了“主页”按钮。 我究竟做错了什么? 另外,如果您对如何更好地完成此任务有任何建议,请告诉我们!

我会得到这样的文件名,而不是:

 var pathname = window.location.pathname.split("/"); var filename = pathname[pathname.length-1].split(".")[0]; alert(filename); 

你的正则表达式不正确。

 var loc_match = window.location.href.match(/(\w+)\.php/); activate(loc_match ? loc_match[1] : "home"); 

我没有解决方案,但我认为正则表达式是有缺陷的。 您是否尝试将结果存储在变量和console.log中?

我实际上已经实现了这样的东西。 这是我的代码:

 var currentPage = window.location.pathname.toLowerCase().split('/').reverse()[0].split('#')[0].split('?')[0]; if (!currentPage || currentPage == '') { currentPage = 'default.aspx'; } $('#nav li').removeClass('current').each(function() { var href = $(this).find('a').first().attr('href'); if (href && href.toLowerCase().indexOf(currentPage) >= 0) { $(this).addClass('current'); } }); 

这会考虑任何查询字符串或搜索可能在URL中。 使用reverse()可能不是最有效的方法,但它确实有效。

当你将regexp声明为新的RegExp对象时,你必须使用双反斜杠转义符号(而不是一个反斜杠,当你只是指定文字像var a = /\w/i; ); 因此,您的代码应该在一些reg exp更正后工作:

 var loca = document.location.href; var pattern = new RegExp("[\\w]*(?=\\.php)","i"); // Get document location and specific page. if(pattern.test(loca)) { activate(pattern.exec(loca)); } else { activate("home"); } // Activate a button function activate(bName) { $(".button[name=" + bName + "]").addClass('active') } 

如前所述,将类分配给活动元素会更容易。