如何基于URL将活动类添加到导航菜单 [英] How to Add Active Class to a Navigation Menu Based on URL

查看:114
本文介绍了如何基于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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆