jquery - 事件 URL 菜单的事件类(不使用 LI)

标签 jquery html css

我有这个 HTML 代码,我想向事件链接中包含的 div 添加一个“事件”类。 (我故意在不使用无序列表的情况下创建了这个导航。)

<nav role="navigation" id="navigation">
<a href="rings-c-24.html" title="Rings"><div class="primary-navigation">Rings</div></a>
<a href="earrings-c-23.html" title="Earrings"><div class="primary-navigation">Earrings</div></a>
<a href="necklaces-c-26.html" title="Necklaces"><div class="primary-navigation">Necklaces</div></a>
<a href="bracelets-and-bangles-c-22.html" title="Bracelets & Bangles"><div class="primary-navigation">Bracelets & Bangles</div></a>
</nav><!-- end of navigation-->

我试过类似的方法,但我确定我没有正确引用我的 parent 和 child 。请帮忙,谢谢!

$(function(){
    var current = location.pathname;
    $('.primary-navigation').each(function(){
        var $this = $(this).parent();
        // if the current path is like this link, make it active
        if($this.attr('href').indexOf(current) !== -1){
            $this.addClass('active');
        }
    })
}) 

最佳答案

您可以为此使用属性选择器:

$("#navigation a[href='"+location.pathname+"']").find(".primary-navigation").addClass("active");

或者如果您想将类添加到 <a>标签:

$("#navigation a[href='"+location.pathname+"']").addClass("active");

关于jquery - 事件 URL 菜单的事件类(不使用 LI),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20759858/

相关文章:

javascript - 点击两次即可激活? javascript onclick 问题

javascript - 将innerHTML更改回其原始值,但使用JavaScript获取 "undefined"

css - 如何嵌套此 scss 以使其仍按预期运行

html - polymer :不同样式的核心图标按钮

html - 如何使我的 div 背景具有不透明度而不是文本?

javascript - 为什么我的 3 个 Highcharts 饼图/图表中只显示了 2 个

php - jquery .load() 无法安装表

java - 如何将模型解析为 ajax post 调用

css - 全高 div : make faux column have a fixed width

javascript - 动态改变按钮的颜色