根据最终网址路径段向列表项添加类

Add class to list item based on final URL path segment

本文关键字:列表 添加 路径      更新时间:2023-09-26

all!菜鸟警报。当 a 的 href 值包含当前页面的结尾时,我正在尝试添加类"active"以列出导航中的项目。

例如,如果我在"http://www.website.com/about/overview/"上,我希望包含 a 且 href 为 "/overview/" 的 li 使类处于活动状态。

<ul>
    <li><a href="http://www.website.com/about/overview/">Overview</a></li>
    <li><a href="http://www.website.com/about/staff/">Staff</a></li>
    <li><a href="http://www.website.com/about/membership/">Membership</a></li>
</ul>

如果我将"lastSegment"更改为"/overview",下面的脚本有效,但我需要脚本是动态的并抓取当前 url 的末尾。

<script type='text/javascript'>
$(function () {

    $("ul > li a[href*='lastSegment']").closest('li').addClass('active');
});
</script>

我想我可以像这样抓住当前网址的结尾

var url = 'window.location.href';
var lastSegment = url.split('/').pop();

但我显然不知道如何在第一个脚本中使用"lastSegment"变量。有什么想法吗?

欢迎来到 Stack Overflow。

如果将选择器更改为$("ul > li a[href$='" + lastSegment + "']")该部分将起作用。

但你也必须改变

var url = 'window.location.href';

var url = window.location.href;

var url = 'window.location.href'; 

这是字符串,您总是会在此行中得到"window.location.href"

var lastSegment = url.split('/').pop();

这是不正确的,您需要获取当前路径

 var url = window.location.href;

您需要将此变量添加到选择器

$("ul > li a[href*='lastSegment']").closest('li').addClass('active');

你可以这样做

$("ul > li a[href*=" + lastSegment + "]").closest('li').addClass('active');