dousha4804 2015-08-27 01:12
浏览 29

jQuery - 将活动类添加到菜单中的子菜单

I have a sidebar menu which I am using for navigation throughout my website and I am wanting to be able to dynamically add the active class to the appropriate menu item. I've tried using the code bellow but It doesnt seem to be doing anything.

    var page = window.location.href.substr(window.location.href.lastIndexOf("/")+1);
    $('ul li a[href="'+ page +'"]').parent().addClass('active');
    $('ul li a').filter(function() {
        return this.href == page;
    }).parent().addClass('active');

I might have my syntax wrong for the selector so below I have included a snippet of the sidebar.

    <div id="sidebar" class="nav-collapse ">
        <ul class="sidebar-menu" id="nav-accordion">
            <li>
                <a href="dash.php">
                    <i class="fa fa-dashboard"></i>
                    <span>Home</span>
                </a>
            </li>

            <li class="sub-menu">
                <a href="javascript:;" >
                    <i class="fa fa-cogs"></i>
                    <span>Tools</span>
                </a>
                <ul class="sub">
                    <li><a href="index.php">Uptime</a></li>
                </ul>
            </li>
        </ul>
    </div>
  • 写回答

3条回答 默认 最新

  • doulan8152 2015-08-27 01:38
    关注

    window.location does not return a string. If you open your browser's developer tools and inspect it you will see it is an object. Not sure what value you're after, but I think you would start with the pathname property e.g., var path = window.location.pathname; then do some regex to get the page name if necessary.

    评论

报告相同问题?

悬赏问题

  • ¥15 yolov8边框坐标
  • ¥15 matlab中使用gurobi时报错
  • ¥15 WPF 大屏看板表格背景图片设置
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真