【问题标题】:addClass('active') with window.location.pathname - url is without file extensionaddClass('active') with window.location.pathname - url 没有文件扩展名
【发布时间】:2015-01-30 15:25:07
【问题描述】:

这是我在这里的第一个问题,我被卡住了,没有找到我想要的答案。我有这种情况,我想.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

【问题讨论】:

  • 在你的 PHP 中做这个服务器端会更好(也更可靠)
  • 你总是可以在比较之前对字符串进行正则表达式格式化

标签: javascript jquery url navigation


【解决方案1】:

Phillip100 - 谢谢你,你帮了我这个,也许不是直接的,但是你的代码迫使我从另一个角度看,我没有替换,我只是添加了扩展! =D

对我有用的代码是:

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

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

【讨论】:

    【解决方案2】:

    //100% 工作

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

    【讨论】:

    • 这会从路径名创建一个新的正则表达式,这可能会产生副作用。请参阅MDN 了解更多信息。你会想要 .includes 或 .indexOf
    猜你喜欢
    • 1970-01-01
    • 2023-04-05
    • 1970-01-01
    • 1970-01-01
    • 2016-12-24
    • 1970-01-01
    • 2012-03-04
    • 2012-12-24
    • 2023-04-05
    相关资源
    最近更新 更多