【问题标题】:Add active class to an li when on URL [duplicate]在 URL 上时将活动类添加到 li [重复]
【发布时间】:2020-01-30 14:07:25
【问题描述】:

我正在尝试根据活动 URL 向 li 添加一个活动类, 这是我得到的,不幸的是,当

<li class="scroll"><a href="index.php">Home</a></li>

它会在以下情况下工作:

<li class="scroll"><a href="">Home</a></li>

jQuery 是:

jQuery(function($) {
     var path = window.location.href;
     if ( path == '' ) {
       path = 'index.php';
     }
     $('ul li a').each(function() {
      if (this.href === path) {
       $(this).parent().addClass('is-current');
      }
     });
    });

谢谢!

【问题讨论】:

  • console.log(path,path===this.href)
  • $(function() { var path = window.location.pathname; if ( path === '' ) path = 'index.php'; $('ul li a[href='+path+']').parent().addClass('is-current'); });

标签: jquery


【解决方案1】:

发生这种情况的原因是 URL 不是mysite.com/index.php

您需要根据 URL 路径设置活动状态。

https://developer.mozilla.org/en-US/docs/Web/API/Location

window.location.pathname 是您正在寻找的。这将返回带有前导 / 的 URL 结尾,您可以根据该字符串进行检查。

如果您在基本 URL(通常是主页)上,检查将不包含路径,如果您在域的子页面上,则可以检查例如:

// site.com/about
const path = window.location.pathname

if (path === '/about') {
  $('li').addClass('active')
}

【讨论】:

  • 谢谢! jQuery(function($) { var path = window.location.pathname; if ( path == '' ) { path = 'index.php'; } $('ul li a').each(function() { if (this.pathname === path) { $(this).parent().addClass('is-current'); } }); });
【解决方案2】:

这是因为 window.location.href 返回完整的 url,意思类似于

www.example.com/folder/index.php

也许this 可以帮助您,因为您只需要文件名。

【讨论】:

  • 除非您可以帮助 OP 解决问题,否则这并不是真正的答案。你只是在描述问题。
  • 你是对的。已编辑。
猜你喜欢
  • 1970-01-01
  • 2012-07-31
  • 2013-07-02
  • 2023-04-04
  • 2023-03-31
  • 2014-02-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多