dttphb59319 2015-05-18 06:49
浏览 21
已采纳

获取URL的基本名称,然后将活动类放入导航栏

Example Link: http://localhost/test/page.php

I have a JavaScript code that will put an active class to a navbar if the url of that href ==== current_url.

Current JavaScript (Only puts active class to sidebar)

<script type="text/javascript">
jQuery(function($) {
    var path = window.location.href; // because the 'href' property of the DOM element is the absolute path
    $('ul a').each(function() { 
        if (this.href === path) {
            $(this).addClass('sub-menu active');
            $(this).parent().closest("li").addClass('active');
            $(this).parent().parent().closest("li").addClass('active');
        }
    });
}); 
</script>

I want to make it work also if the link has a page.php?success. There will also be an active class as long as the page.php is there regardless of what is after the ?.

I've tried the following script below to extract the basename but now it doesn't work at all, pages with or without ?.

Tried script (Supposed to put active class to sidebar even if the url has page.php?success in it.

<script type="text/javascript">
jQuery(function($) {
    var patharray = window.location.pathname.split( '/' );
    var reallink = patharray[2]; 
    $('ul a').each(function() { 
        if (this.href === reallink) {
            $(this).addClass('sub-menu active');
            $(this).parent().closest("li").addClass('active');
            $(this).parent().parent().closest("li").addClass('active');
        }
    });
}); 
</script>

With the example link above. The script returns page.php And the href's inside the navbar are just page1.php, page2.php etc... So I know it should work since the retrieved reallink is equal to the href of the navbar.

My sidebar

<li class="sub-menu"> // Sidebar with no submenu
  <a class="" href="page1.php">
    <i class="icon-calendar"></i>
    <span>This is page 1</span>
  </a>
</li>
<li class="sub-menu"> // Sidebar with a submenu
  <a href="javascript:;" class="">
    <i class="icon-group"></i>
    <span>This has sub pages</span>
    <span class="arrow"></span>
  </a>
  <ul class="sub">
    <li><a class="" href="page2.php">This is page 2</a></li>
    <li><a class="" href="page3.php">This is page 3</a></li>
  </ul>
</li>

So the first JavaScript puts an active class both to the parent and the child if the href = url is met. But with the 2nd script nothing works.

  • 写回答

1条回答 默认 最新

  • duanlieshuang5330 2015-05-18 06:56
    关注

    I guess changing this line in the First script will make it work

    var path = window.location.href.split( '?' )[0];
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 关于用python写支付宝扫码付异步通知收不到的问题
  • ¥50 vue组件中无法正确接收并处理axios请求
  • ¥15 隐藏系统界面pdf的打印、下载按钮
  • ¥15 MATLAB联合adams仿真卡死如何解决(代码模型无问题)
  • ¥15 基于pso参数优化的LightGBM分类模型
  • ¥15 安装Paddleocr时报错无法解决
  • ¥15 python中transformers可以正常下载,但是没有办法使用pipeline
  • ¥50 分布式追踪trace异常问题
  • ¥15 人在外地出差,速帮一点点
  • ¥15 如何使用canvas在图片上进行如下的标注,以下代码不起作用,如何修改