根据网址分配不同的类

时间:2012-11-30 11:22:22

标签: javascript html css

我需要动态组合“活动”类来管理某些链接的样式。 我有这个代码,但不起作用..

<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}

任何人都有任何建议或看到它?

3 个答案:

答案 0 :(得分:1)

在你的JS中你这样做:

$('.livello2 a[href="/' + path + '"]')

(假设您已在选择器的开头添加了该点)将被转换(在计算path变量之后)为

之类的内容
$('.livello2 a[href="/Concerti.php"]')

但代码中的实际href属性以.(点)开头,如

href="./Concerti.php"

所以你需要将上面的JS片段更新为

$('.livello2 a[href="./' + path + '"]')

答案 1 :(得分:0)

替换这个

$('livello2 a[href="/' + path + '"]')

这一个

$('.livello2 a[href="/' + path + '"]')

答案 2 :(得分:0)

除了@Murali Prasanth关于在JS片段中添加点的答案之外,我建议确保在结束</body>之后立即放置你的javascript块。如果它不能正常工作,因为页面还不知道.livello2 - 它还没有被加载。所以,要么在关闭</body>之前把JS放到正确的位置,要么像这样包装你的javascript代码:

<script type="text/javascript" language="javascript">  
    $(document).ready(function () {
        function locationPathname(){
        …
        }
    });
</script>
相关问题