问题描述
更新
let path = document.querySelector("#path");
path.innerHTML = "Page pathname is: " + location.pathname;
所以对于链接 private.PHP?folderid=0
的路径名是 private.PHP
发现这确实让我失望,但这个问题的主题保持不变。
结束更新
我的链接结构如下:
<li role="presentation" class="pane-link pane-folder $navclass[deletedthreads]" Nowrap="Nowrap">
<a class="smallfont" href="moderation.PHP?$session[sessionurl]do=viewthreads&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&type=deleted">$vbphrase[posts]</a>
</li>
还有更多,但它们都共享类 pane-link
JS 是我在苦苦挣扎,如果当前页面是链接页面,我正在尝试将类 active
添加到 li
元素。
我尝试使用的方法 location.pathname
我发现无法读取我的完整链接。 (我相信)
这就是我所拥有的(不工作)
if("a[href*='" + location.pathname + "']") {
$("a[href*='" + location.pathname + "']").parent().addClass("active");
}
注意 并非我列表中的所有链接都包含如上例所示的变量。有些链接就像 private.PHP?do=newpm
一样简单,我不确定链接中的变量是否会影响 Javascript 位置。
我想知道,如果我的链接是当前页面,我如何向我的 li
添加一个类?
解决方法
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 库
,我在应该使用 location.pathname
的地方使用了 window.location
来代替它给了我想要的结果。
我的最终脚本变成了:
if("a[href*='" + window.location + "']") {
$("a[href*='" + window.location + "']").parent().addClass("active");
}