将URL路径与<a>attr('href')来动态更新.active类
Matching the URL path with <a> attr('href') to dynamically update .active class
嘿,伙计们,我在navbar.php文件中有我的navbar代码,HTML看起来如下:
<nav role="navigation" class="nav" >
<ul class="menu" id="menu">
<li class="active"><a href="index.php">
Home</a></li>
<li><a href="about-us.php">About us</a></li>
<li><a href="products.php">Products</a>
<ul class="submenu">
<li class="active">product-1</li>
<li>product-2</li>
<li>product-3</li>
<li>product-4</li>
<li>product-5</li>
<li>product-6</li>
</ul>
</li>
<li><a href="contactus.php">Contact us</a></li>
</ul>
</nav>
在page load上,我运行了一个非常简单的Jquery片段来运行所有的<a>
,并检查其href是否与浏览器中的url(实际上是url的末尾,例如index.php)匹配。
所以我有以下Jquery片段:
$(document).ready(function(){
var _urlpath = $(location).attr('pathname');
console.log(_urlpath); // this does't print out the desired version , it prints `/lala-v1/about-us.php"`
$('#menu > li').each(function(){
var _str = $(this).find('a').attr('href');
console.log(_str); // these print out the desired output eg. index.php
if(_str == _urlpath){
console.log(_str + _urlpath);
}
});
});
检查我的评论,我的困难是在Jquery的第二行获得正确的url路径。我浏览了这篇文章,我看到的Jquery选项都不会返回我看到的URL的末尾部分。
那我该怎么办?我被卡住了,在JS/Jquery中有办法解决这个问题吗。
我对这两个领域都是新手,所以我很感激任何帮助。
试试这个:
var _urlpath = window.location.pathname.split('/').pop();
// or: $(location).attr('pathname').split('/').pop();
使用prop()
而不是attr()
,它将返回绝对路径,而不是为属性设置的字符串。
比较文件名可能会失败,不同目录中可能存在名称相同的文件。
$(document).ready(function(){
$('#menu > li').each(function(){
var _str = $(this).find('a').prop('href');
if(_str == location.href){
$(this).css('background','red');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="menu" id="menu">
<li class="active"><a href="index.html">
Home</a></li>
<li><a href="about.html">About us</a></li>
<li><a href="">This is the current page, should be highlighted by jquery</a></li>
<li><a href="products.html">Products</a>
<ul class="submenu">
<li class="active">product-1</li>
<li>product-2</li>
<li>product-3</li>
<li>product-4</li>
<li>product-5</li>
<li>product-6</li>
</ul>
</li>
<li><a href="contactus.html">Contact us</a></li>
</ul>
这些值不匹配,因为/lala-v1/about-us.php !== about-us.html
,加上您使用".php"提供的页面和链接都是".html"。您可以使用它来获得正确的值:window.location.pathname.split('/').pop();
相关文章:
- 根据滚动位置动态更改href
- 将URL路径与<a>attr('href')来动态更新.active类
- 如何使fancybox href动态
- Javascript/jQuery链接/href补充的动态文本
- HTML href动态语法
- 如何动态更改href引用
- 如何在html href标记中动态放置当前网址
- 如何使用 JavaScript 动态点击“href 链接”
- 动态设置 href 标记
- 单击事件以获取 href 标记(动态创建)
- 将数据参数(不是查询参数)提供给 window.location.href ?创建动态文件
- 带有来自数据库的动态链接的花式框 href (asp.net)
- 在 Twitter Bootstrap 3.0 中动态设置弹出框值,并在滚动更新时使用 href
- 从 JavaScript 函数 WebDriver 访问动态生成的 HREF
- 将 HREF 添加到 JQuery 动态填充的选择
- 引导按钮组以动态更改文本、HREF 和图标 - JQuery
- AngularJS href 没有获得动态值
- 动态替换 href
- AngularJs的ng-href动态链接,作用域没有更新/工作
- Href动态链接