我有下面的菜单,我想将active
类添加到<li>
,其中包含用户当前正在查看的页面的链接。
<ul class="sidebar-menu">
<li class="treeview"><a href="#"><i class="fa fa-dashboard"></i> <span>Text</span></a></li>
<li class="treeview"><a href="#"><i class="fa fa-th"></i><span>Subtext 1</span><i class="fa fa-angle-left pull-right"></i></a>
<ul class=" treeview-menu">
<li><a href="#"><i class="fa fa-circle-o"></i> Text 1</a></li>
<li><a href="#"><i class="fa fa-circle-o"></i> Text 2</a></li>
</ul>
</li>
</ul>
我试过这个jQuery代码,但它对我不起作用:
$(function(){
var url = window.location.pathname,
urlRegExp = new RegExp(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
$('.treeview a').each(function(){
// and test its normalized href against the url pathname regexp
if(urlRegExp.test(this.href.replace(/\/$/,''))){
$(this).addClass('active treeview-menu');
}
});
});
答案 0 :(得分:0)
尝试以下方法。它找到具有当前URL的链接作为其href
,找到其父级,并将类应用于父元素。
$(document).ready(function() {
$('a[href="' + this.location.pathname + '"]').parent().addClass('active treeview-menu');
});
答案 1 :(得分:0)
为了完成这项工作,我对您的代码进行了一些更改:
a
,而是按照您的指定将其添加到li
。treeview
添加到所有li
。href
属性来获取链接的URL,而不是使用pathname
属性,因为它需要匹配函数顶部的location.pathname
。您当然可以与主机名进行比较,重点是您需要将苹果与苹果而不是橙子进行比较。$(function(){
//Use the function removeSlash to clean up URL instead of using RegExp.
var url = removeSlash(window.location.pathname);
//Loop through the treeview elements (the li) instead of the a.
$('.treeview').each(function(){
//Find the href of the a in the li.
var link = $(this).find('a')[0];
//Use the link we just found instead of this.
//Also, instead of href, use pathname. That will give just the path, not the host.
if(url == removeSlash(link.pathname)) {
//This referes to the li, so we can keep this line of code as it is.
$(this).addClass('active');
}
});
});
function removeSlash(url) {
//Remove leading slash, if there is one.
if(url.charAt(0) == '/') url = url.substring(1);
//Remove trailing slash, if there is one.
if(url.charAt(url.length-1) == '/') url = url.substring(0, url.length-1);
//Return the result.
return url;
}
工作JSFiddle。请注意,有一些案例可能无效。例如,如果当前网址为http://example.com/site.php?x=4
且链接的href
为/site.php
,我不确定会发生什么。您应该能够通过修改removeSlash
函数来实现处理这种情况的方法。