查找当前导航项并将 class 分配给 li

Find current nav item and assign class to li

我正在使用下面的代码将 active class 分配给当前导航项。

$(function () {
  var page = window.location.pathname,
  find = new RegExp(page == '/' ? window.location.origin + '/?$' : page.replace(/\/$/, ''));
  $('nav a').each(function () {
    if (find.test(this.href.replace(/\/$/, ''))) {
      $(this).addClass('active');
    }
  });
});

如何使用 parent 将 class 分配给 li 标签?

如果我没有理解你的问题,你想将 class 添加到标签的父级。这就是您的操作方式。

$(this).parent().addClass('active');