我需要动态地设置“active”类来管理某些链接的样式。 我有这段代码,但不起作用..
<script type="text/javascript" language="javascript">
function locationPathname(){
var path = window.location.pathname.split('/');
path = path[path.length-1];
alert(path);
if (path !== undefined) {
$('livello2 a[href="/' + path + '"]').addClass('active');
}
}
</script>
和 html:
<div class="livello2">
<div class="live">
<a href="./Live.php"><img src="live_off.png"></a>
</div>
<nav class="menu">
<ul>
<a href="./index.php" ><li>HOME</li></a>
<a href="./Concerti.php"><li>CONCERTI</li></a>
</ul>
</nav>
</div>
CSS:
.active{background-color:red}
有人有任何建议或看到了吗?
最佳答案
在你的 JS 中你这样做:
$('.livello2 a[href="/' + path + '"]')
(假设您在选择器的开头添加了那个点)将(在计算 path
变量之后)转换成类似的东西
$('.livello2 a[href="/Concerti.php"]')
但是代码中的实际 href 属性以 .
(点)开头,如
href="./Concerti.php"
因此您需要将上面的 JS 片段更新为
$('.livello2 a[href="./' + path + '"]')
关于javascript - 根据 url 分配不同的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13644268/