找到当前窗口.路径名包含链接的位置

Find if current windows.pathname contains location to li a href

本文关键字:包含 链接 位置 路径名 窗口      更新时间:2023-09-26

我有这个代码添加一个active类链接到当前页面:

jQuery(function() {
  jQuery('.topmenu li').each(function() {
    var href = jQuery(this).find('a').attr('href');
    if (href === window.location.pathname) {
      jQuery(this).find('a').addClass('active');
    }
  });
});  

这对于完全匹配路径名非常有效,但是我如何才能看到我所在的页面是否是链接的子页面?

当我有这样一个链接:<a href="/top-page-1/sub-page-1/">Sub page 1</a>的代码工作。

当我在/top-page-1/sub-page-1/,但当我在/top-page-1/sub-page-1/sub-sub-page-1/,我没有得到一个active类的链接。有办法吗?

在你的代码中试试:

jQuery(function() {
  jQuery('.topmenu li').each(function() {
    var href = jQuery(this).find('a').attr('href');
    if (window.location.pathname.indexOf(href)>-1) {
      jQuery(this).find('a').addClass('active');
    }
  });
});