获取URL的基本名称,然后将活动类放入导航栏 [英] GET Basename of URL then put active class to navbar
问题描述
示例链接:
http://localhost/test/page.php
我有一个JavaScript代码,如果 href =的网址,它会将
。有效
类放入导航栏=== current_url
I have a JavaScript code that will put an active
class to a navbar if the url of that href ==== current_url
.
当前JavaScript(仅将活动类放入侧边栏)
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>
如果链接有 page.php,我想让它也能正常工作?成功
。只要 page.php
在那里,无论?
之后是什么,都会有一个活动类。
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 ?
.
尝试过的脚本(假设将活动类放到侧边栏,即使网址有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.php
等...所以我知道它应该可以工作,因为检索到的 reallink
等于导航栏的 href
。
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>
因此,如果href = url,则第一个JavaScript将活动类放入父级和子级满足。但是使用第二个脚本没有任何效果。
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.
推荐答案
我想在第一个脚本中更改此行将使其正常工作
I guess changing this line in the First script will make it work
var path = window.location.href.split( '?' )[0];
这篇关于获取URL的基本名称,然后将活动类放入导航栏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!