如何使用 jQuery 将 class 附加到当前页面上的父元素

how to appeand class to parent element on current page with jQuery

更新

我已将页面的路径名打印到页面上,但发现它没有读取请求。

let path = document.querySelector("#path");
path.innerHTML = "Page pathname is: " + location.pathname;

所以对于 link private.php?folderid=0 路径名是 private.php 发现这确实让我失望,但这个问题的主题保持不变。

更新结束

如果 link 是当前页面,我正在尝试将 class 添加到父元素。

我的 link 结构如下:

<li role="presentation" class="pane-link pane-folder $navclass[deletedthreads]" nowrap="nowrap">
  <a class="smallfont" href="moderation.php?$session[sessionurl]do=viewthreads&amp;type=deleted">$vbphrase[threads]</a>
</li>
<li role="presentation" class="pane-link pane-folder $navclass[deletedposts]" nowrap="nowrap">
  <a class="smallfont" href="moderation.php?$session[sessionurl]do=viewposts&amp;type=deleted">$vbphrase[posts]</a>
</li>

还有很多,但他们都共享 class pane-link

JS 是我在挣扎,如果当前页面是 [=58= 的页面,我正在尝试将 class active 添加到 li 元素].

我尝试使用的方法 location.pathname 我发现无法读取完整的 link。 (我相信)

这就是我所拥有的(不工作)

if("a[href*='" + location.pathname + "']") {
  $("a[href*='" + location.pathname + "']").parent().addClass("active");
}

注意 并非我列表中的所有 link 都包含上述示例中的变量。一些 link 和 private.php?do=newpm 一样简单 我不确定 link 中的变量是否影响 Javascript 位置。

我想知道,如果我的 link 是当前页面,我怎样才能将 class 添加到我的 li

我正在使用 location.pathname,我应该使用 window.location 来替换它,这给了我想要的结果。

我的结束脚本变成了:

if("a[href*='" + window.location + "']") {
  $("a[href*='" + window.location + "']").parent().addClass("active");
}

location.href : http://yourwebsite.com/private.php?folderid=0

location.origin : http://yourwebsite.com/

location.pathname : private.php

所以要简单地获取带有参数的路径名,您可以使用 .replace

<script>
    var loc = location.href.replace(location.origin , '');  
    console.log(location);
</script>

检查元素使用 .length

<script>
   if($(element).length){
   }
</script>

所以这两个代码组合起来应该是这样的

<script>
     $(document).ready(function(){
        var loc = location.href.replace(location.origin , '');  
        console.log(loc);
       if($("a.smallfond[href*='"+loc+"']").length){
          $("a.smallfond[href*='"+loc+"']").parent().addClass('active');
       }
     }
</script>

注意:确保包含 jquery 库