嘿,伙计们,我在一个navbar.php文件中有我的导航条代码,这个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>在页面加载中,我运行了一个非常简单的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的第2行获得正确的url路径。我阅读了这文章,我看到的Jquery选项中没有一个会返回我看到的URL的末尾部分。
那我该怎么办?我被困住了,在JS/Jquery中有没有解决这个问题的方法?
我对这两件事都是新手,所以我很感激你的帮助。
发布于 2015-03-02 12:59:54
试试这个:
var _urlpath = window.location.pathname.split('/').pop();
// or: $(location).attr('pathname').split('/').pop();发布于 2015-03-02 13:10:45
使用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>
发布于 2015-03-02 13:05:07
这些值将不匹配,因为/lala-v1/about-us.php !== about-us.html,加上您使用".php“和链接服务的页面都是".html”。您可以使用它获得正确的值:window.location.pathname.split('/').pop();
https://stackoverflow.com/questions/28810359
复制相似问题