查找链接路径从当前链接(javascript)向上的目录

Find link path a directory up from your current link (javascript)

本文关键字:链接 路径 查找 javascript      更新时间:2023-09-26

我有一点javascript,可以在页面上找到一个链接,如果它与当前页面的链接相同,它会将css更改为current。这很好用。但我想做的是扩展它,例如,让相同的链接是mysite.com/blog/post。我希望它进入一个目录,即mysite.com/blog,找到页面上的链接,如果它突出显示它,希望这是有意义的。我的代码是:

<script type="text/javascript">
$(document).ready( function () {
var path = location.pathname;
if ( path )
 $('#sidebar ul.archive a[href$="' + path + '"]').attr('class', 'current');
 }); 
</script>

所以我想我只需要更改var路径就可以找到上面目录的链接,但我不知道该怎么做?

您可以尝试解析location.pathname以删除最右边的目录。例如:

var path = location.pathname;
var parentPath = path.substr(0,path.lastIndexOf('/'));

如果我理解正确的话。。

$('#sidebar ul.archive a').filter(function() {
    return path.match($(this).attr('href'));
}).addClass('current');

例如,如果当前页面是mysite.com/blog/post,这将向链接<a href="/blog">Blog</a>添加类current