我已经从stackoverflow的另一个线程获得了这个jQuery正则表达式。它根据url为当前菜单项添加了一个css类。它看起来像这样:
<script>
$(function () {
// show current menu object highlighted
var url = window.location.pathname,
urlRegExp = new RegExp(url == '/' ? window.location.origin + '/?$' : url.replace(/\/$/, '')); // create regexp to match current url pathname and remove trailing slash if present as it could collide with the link in navigation in case trailing slash wasn't present there
// now grab every link from the navigation
$('nav a').each(function () {
// and test its href against the url pathname regexp
if (urlRegExp.test(this.href)) {
$(this).addClass('current');
}
console.log(url);
console.log($(this).attr('href'));
});
});
</script>
如果路径与链接href中的路径完全相同,则效果很好,但我希望这也适用于当前菜单对象的子页面。这是我的导航:
<nav>
<ul>
<li>
<a href="/Admin/Blogs" title="Blog" style="border-left: 1px solid rgba(0,0,0,.15);">Blog</a>
</li><li>
<a href="/Admin/Shows" title="Shows">Shows</a>
</li><li>
<a href="/Admin/StoreItems" title="Store">Store</a>
</li><li>
<a href="/Admin/Pages" title="Pages">Pages</a>
</li><li>
<a href="/Admin/Menu" title="Menu">Menu</a>
</li><li>
<a href="/Admin/SocialMedia" title="Social media">Social media</a>
</li><li>
<a href="/Admin/ImageGallery" title="Image gallery">Image gallery</a>
</li><li>
<a href="/Admin/MailSettings" title="Mail settings">Mail settings</a>
</li><li>
<a href="/Admin/PageSettings" title="Site configuration">Site configuration</a>
</li>
</ul>
</nav>
让我们说路径是/ Admin / Blogs / Create,我想要突出显示Blog菜单项。目前情况并非如此。 此外,如果我进入/ Admin(即主页),此时所有菜单项都被选中,这是不可取的。
我真的需要花一些时间来正确地学习正则表达式,但我对这个(学校项目)有点匆忙,所以如果有人能帮助我,我将非常感激。
答案 0 :(得分:0)
我让它使用这段代码:
<script>
$(function () {
// show current menu object highlighted
var url = window.location.pathname;
var checkString;
// now grab every link from the navigation
$('nav a').each(function () {
// and test its href against the url pathname
checkString = url.match($(this).attr('href'));
if ((checkString != null && $(this).attr('href') != '/') || (url == $(this).attr('href'))) {
$(this).addClass('current');
}
});
});
</script>
答案 1 :(得分:0)
我能够让它与Mikael的代码一起工作,但它不会使链接处于子页面上的活动状态。我让它使用下面的代码。 href&amp;中的单词匹配将链接置于活动状态的url必须编码,但它适用于我,因为'consumer'是文件夹名称,所有子页面将是/consumer/page.html
$(function () {
// show current menu object highlighted
var url = window.location.pathname;
var checkString;
// keeps the link active on sub pages, 'consumer' is the folder in this instance and all sub pages with be /consumer/page.html
if (url.indexOf("consumer") != -1){
$('#quick-links a').each(function(){
if( $(this).attr('href').indexOf("consumer") != -1){
$(this).parent('li').addClass('active');
}
});
}
// now grab every link from the navigation
$('#quick-links a').each(function () {
// and test its href against the url pathname
checkString = url.match($(this).attr('href'));
if ((checkString != null && $(this).attr('href') != '/') || (url == $(this).attr('href'))) {
$(this).parent().addClass('active');
}
});
});