2015-10-29 104 views
1

我的菜单有问题。我希望活动状态保持在最后点击的链接上。页面重新加载后,菜单活动状态保持点击链接

<ul id="nav"> 
    <li class="active"><a href="?field1="2"&field2="test">products </a></li> 
    <li><a href="?field1="3"&field2="test2">products2 </a></li> 
</ul> 

当我点击products2右侧的表将填充数据库中的字段在url这将刷新页面。我怎么能保持点击链接有积极的类?

回答

1

应将以下工作:

var qs = decodeURIComponent(location.search); 
$('a[href="' + qs + '"]').parents('li').addClass('active'); 

location.search,你会发现这是appenden到您的网址查询字符串。

decodeURIComponent将解码您的网址,以避免例如空白的%20

$('a[href="' + qs + '"]')选择a -tag其中href -attribute对应于您的查询字符串。

但我会建议删除从您的网址参数的额外"里面你href

<ul id="nav"> 
    <li class="active"><a href="?field1=2&field2=test">products </a></li> 
    <li><a href="?field1=3&field2=test2">products2 </a></li> 
</ul> 

如果无法删除引号,你必须逃脱他们的属性,选择工作。


参考

location.search

decodeURIComponent

jQuery attribute selector

.parents()

.addClass()

+0

这一个作品!感谢经验丰富 –

0

您可以检查url,并将其应用于相关元素。这是可以做到的服务器端,或

喜欢这个

//if url contains "field1=3" then add the class "selected" to element "tab2" 
if (window.location.href.indexOf("field1=3") > -1) { 
    $("#tab2").addClass("selected") 
} 

值和标签显然应该在一些whay是结构化的客户端(我看到你的客户端技术的标签这一点),但你的要旨。

+0

你能解释一下吗?对不起,我对这个问题总是很高兴。并且我不使用标签我只想要链接。 –

0

使用jQuery,你可以在你的场景中试试这个。

var currentPath="?"+window.location.href.split("?")[1]; 
    $("a[href='"+currentPath+"']").parent().addClass("active"); 
0

简单但难看的解决方案是,在product2页面上添加手动高亮显示链接的代码。

或者如果问题出在所有链接上,并且将来会有n个链接可用,那么您的代码应该更加结构化。在这种情况下,您可以将公共代码用于处理这种常见工作(突出显示侧栏上的链接)在常用js文件之一中。而不是放在所有的页面上。

相关问题