单击带有Jquery的菜单链接时添加活动的类 [英] Add class active when clicking the menu link with Jquery

查看:48
本文介绍了单击带有Jquery的菜单链接时添加活动的类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有HTML

<div id="top" class="shadow">
  <ul class="gprc"> 
    <li><a href="http://www.domain.com/">Home</a></li> 
    <li><a href="http://www.domain.com/link1/">Text1</a></li> 
    <li><a href="http://www.domain.com/link2/">Text2</a></li> 
    <li><a href="http://www.domain.com/link3/">Text3</a></li> 
    <li><a href="http://www.domain.com/link4">Text4</a></li> 
  </ul> 
</div>

和JQUERY

$(function () {
    var url = window.location.pathname,
        urlRegExp = new RegExp(url.replace(/\/$/, '') + "$");
    $('#top a').each(function () {
        if (urlRegExp.test(this.href.replace(/\/$/, ''))) {
            $(this).addClass('active');
        }
    });    
});

问题是,当我单击主页"链接时,所有选项卡都正在上课,并且不明白为什么.我需要它来使第一个链接没有任何活动的课程.

The problem is that when i click on the Home link all tabs are getting active class and don't understand why. I need it for the first link to not get any active class.

推荐答案

我也在寻找这种解决方案,并且已经测试了您的代码.在第一种方法中,所有链接都突出显示,当我单击其他链接时,它可以正常工作.问题出在主页上,因为突出显示了所有链接,因为加载页面时没有收到未接收到事件",理论上,如果您发送命令或单击每个链接,该代码将起作用.为了停止这种行为,我找到了上面的答案之一的代码,添加此代码并将".sibling()"更改为".previousSibling()"

I'm also looking for this solution and I have tested your code. On the first approach all links are highlighted and when I click other links it is working properly. The problem was on the home page because all links are highlighted because there is "no event been received" when the page is loaded, the code will work if you send a command or by clicking each links, theoretically. To stop this behavior, I found this code to one of the answers above, add this code and change the ".sibling()" to ".previousSibling()"

$(this).parent().sibling().find('a').removeClass('active');

.sibling()"将在链接的末尾突出显示,将其更改为".previousSibling()",因此它将转到第一个(Li)

".sibling()" will highlighted at the end of your links change it to ".previousSibling()" so it will go to first (Li)

$(this).parent().previoussibling().find('a').removeClass('active');

您的代码将如下所示:

    $(function () {
    var url = window.location.pathname,
        urlRegExp = new RegExp(url.replace(/\/$/, '') + "$");
    $('#top a').each(function () {
        if (urlRegExp.test(this.href.replace(/\/$/, ''))) {
            $(this).addClass('active');
            $(this).parent().previoussibling().find('a').removeClass('active');
        }
    });    
});

这篇关于单击带有Jquery的菜单链接时添加活动的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆