如何基于URL将活动类添加到导航菜单 [英] How to Add Active Class to a Navigation Menu Based on URL
问题描述
我对此有疑问,它处于活动状态时无法保持样式.如何基于URL将活动类添加到导航菜单中
I have problem about this, it can't keep style while it is active. How to Add Active Class to a Navigation Menu Based on URL
<div class="admin_nav">
<ul>
<li><a href="admin.php">main</a></li>
<li><a href="?do=add_menu">manu</a></li>
<li><a href="?do=add_news">news</a></li>
<li><a href="#">123</a></li>
<li><a href="#">123</a></li>
<li><a href="#">123</a></li>
<li><a href="#">123</a></li>
</ul>
</div>
$(function() {
var pgurl = window.location.href.substr(window.location.href.lastIndexOf("/")+1);
$(".admin_nav ul li a").each(function(){
if($(this).attr("href") == pgurl || $(this).attr("href") == '' )
$(this).addClass("newclass");
})
});
对此有任何解决方案吗??
any solution about this????
推荐答案
您的代码适用于恰好以/admin.php
,/?do=add_news
和/#
Your code works for pages that exactly end in /admin.php
, /?do=add_news
and /#
例如对于URL http://example.com/?do=add_news
,它将起作用,但是对于http://example.com/foobar.html?do=add_news
,它将不起作用(因为foobar
在?do=add_news
前面).
E.g. for the URL http://example.com/?do=add_news
it will work, but for http://example.com/foobar.html?do=add_news
it won't work (because of the foobar
in front of the ?do=add_news
).
如果您只担心URL的最后部分包含 href字段中的文本,则可以将if语句更改为:
If you're only worried about if the final part of the URL contains the text in the href fields, you could change your if statement to:
if($(this).attr("href") == '' || pgurl.indexOf($(this).attr("href")) > -1)
$(this).addClass("newclass");
这篇关于如何基于URL将活动类添加到导航菜单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!