addClass('active') with window.location.pathname - u

addClass('active') with window.location.pathname - url is without file extension

本文关键字:location pathname window active addClass with      更新时间:2023-09-26

这是我在这里的第一个问题,我被困住了,没有找到我想要的答案。我有这种情况,我想.addClass('active')导航链接。如果我的window.location.pathname具有像.html.php这样的扩展名,它的效果很好。

我通过 .htaccess 有"不错"的 URL,它隐藏了文件的扩展名,看起来像这样:

http://mydomain/biography 而不是 http://mydomain/biography.php

所以这是我写

的代码.HTML

    <nav>
       <ul>
         <li><a href="index.php">Home</a></li>
         <li><a href="biography.php">Bio</a></li>
         <li><a href="somelink.php">Something</a></li>
         <li><a href="contact.php">Contact</a></li>
       <ul>
    </nav>

jQuery

$(document).ready(function() {
    $("nav [href]").each(function() {
    if (this.href == window.location.href) {
        $(this).addClass("active");
        }   
    });
 });

我认为在这种情况下不需要.htaccess代码

有没有办法解析this.href并排除文件扩展名(在我的情况下.php),或者有更好的方法来解决这个问题?

提前感谢! =D

> 菲利普100 - 谢谢伙计,你帮助了我解决这个问题,也许不是直接的,但你的代码迫使我从其他角度看它,我没有替换,我只是添加了扩展! =D

对我有用的代码是:

$(document).ready(function() {
  var location = window.location.href + '.php';        
   $("nav [href]").each(function() {
    if (this.href == location) {
    $(this).addClass("active");
}  

试图通过路径名让它工作,但 href 也有帮助,有了这段代码,我得到了我想要的,感谢所有帮助过的人! =D

//100% 工作

$("nav [href]").each(function() {
      var pathname = window.location.pathname;
      var plink = this.href.search(pathname);
      if(plink > 0){
         $(this).addClass("current");
      }
    });