更新
我已经将页面的路径名打印到页面上,发现它没有通过请求读取。
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
因此,要简单地获得带有params的路径名,可以使用.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");
}