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

时间:2015-05-18 06:49:34

标签: javascript php

  

示例链接:http://localhost/test/page.php

我有一个JavaScript代码,如果active的网址为href ==== current_url,则会将<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> 类放入导航栏。

  

当前JavaScript(仅将活动类放入侧边栏)

page.php?success

如果链接有page.php,我也想让它工作。只要??之后,就会有一个活跃的班级。

我已尝试使用以下脚本来提取基本名称,但现在它根本不起作用,包含或不包含?的页面。

  

尝试过的脚本(假设将活动类放入侧边栏,即使网址已成功获得page.php <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>

page.php

使用上面的示例链接。该脚本返回href导航栏内的page1.php只是page2.phpreallink等...所以我知道它应该有效,因为检索到的{{1} }等于导航栏的href

  

我的侧边栏

<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>

因此,如果满足href = url,第一个JavaScript会将活动类放入父级和子级。但是第二个脚本没有用。

1 个答案:

答案 0 :(得分:3)

我想在第一个脚本中更改此行将使其正常工作

var path = window.location.href.split( '?' )[0];