javascript 使用 Jquery 单击菜单链接时添加活动类

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19639287/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 16:17:48  来源:igfitidea点击:

Add class active when clicking the menu link with Jquery

javascripthtml

提问by Adrian

I have HTML

我有 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>

and JQUERY

和 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.

问题是,当我单击主页链接时,所有选项卡都处于活动状态,但不明白为什么。我需要它作为第一个链接而不是获得任何活动课程。

回答by Bharath R

Check this , this will only activates clicked tab , remove active for all and then add for the one clicked

检查这个,这只会激活单击的选项卡,删除所有活动,然后添加一个单击的选项卡

$("#top a").click(function() {
    $('a').removeClass('active');
    $(this).addClass("active");
});

Check this

检查这个

回答by Dennis Castillo

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()"

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

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

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

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

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

Your code will be like this:

您的代码将是这样的:

    $(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');
        }
    });    
});

回答by Scott Rowell

You're running a foreachloop on all <a>tags within your #topdiv. So of course it'll add the class activeto all of them.

您正在div 中的foreach所有<a>标签上运行循环#top。因此,它当然会将类添加active到所有这些类中。

I think what you're trying to do is this: http://jsfiddle.net/rLddf/4/

我认为你想要做的是:http: //jsfiddle.net/rLddf/4/

I used the clickevent instead.

我改用了这个click事件。

editswitched link to Kristof Feys example - more efficient.

编辑切换到 Kristof Feys 示例的链接 - 更高效。

回答by user7270348

try this...

试试这个...

$(function() { 
    $('#yourMenu a').each(function(){
        $current = location.href;
        $target= $(this).attr('href');
            if ( $target== $current) 
            {
                $(this).addClass('active');
            }
    });
});

回答by Pedz

I came across the same issue and I found it easier to just add an additional if statement so that the function would fire on all pages except the home page which met my needs.

我遇到了同样的问题,我发现添加一个额外的 if 语句更容易,这样该函数就会在除满足我需要的主页之外的所有页面上触发。

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

You could also add in an else statement to show an active link on the homepage by targeting the link directly if required.

如果需要,您还可以添加 else 语句以通过直接定位链接在主页上显示活动链接。

回答by Manisha Agarwal

You may try this out. It will help you:

你可以试试这个。它将帮助您:

<script type="text/javascript">
    $(function () {
        $('#sidebar li a').each(function () {
            var path = window.location.pathname;
            if (path.indexOf('?') > 0) {
                var current = path.indexOf('?');
            }
            else {
                var current = path;
            }
            var url = $(this).attr('href');
            var currenturl = url.substring(url.lastIndexOf('.') + 1);
            if (currenturl.toLowerCase() == current.toLowerCase()) {
                $(this).addClass('active');
                var par = $(this).parent();
                par.addClass('open');
            }
        });
    });
</script>

回答by Dhaval Marthak

I think you need something like this:

我认为你需要这样的东西:

$(function () {
    $("#top a").click(function(e){
        e.preventDefault();
        $(this).addClass('active');
        $(this).parent().siblings().find('a').removeClass('active');
    });
});

Fiddle Demo

小提琴演示