简体   繁体   中英

How to use jQuery to style active link list items

I am using jQuery to check if the browser URL matches the URL in my link href, the issue is after my check I am trying to set the li tag class that the link matches to be "active", but this code below is setting the link tag as active not the li tag

    $(function(){
        var current = location.pathname;
        $('#nav li a').each(function(){
            var $this = $(this);
            // if the current path is like this link, make it active
            if($this.attr('href') === current){
                $this.addClass('active');
            }
        })
    }) 

this refers to the a element not the li you are thinking which is actually the parent of the current element ( a ).

You have to target the parent()

$this.parent().addClass('active');

OR: Using .closest()

$this.closest('li').addClass('active');

Hello

You can try to use this

 $(document).ready(function () { $(".nav li").click(function () { $(".nav li").removeClass("active"); $(this).addClass("active"); }); });
 .headerTopMenu ul { padding: 0; margin: 0; list-style: none; } .headerTopMenu li { display: inline-block; padding: 0 15px; } .headerTopMenu li a { display: inline-block; text-decoration: none; font-size: 16px; line-height: 40px; color: #000; position: relative; -webkit-transition: all 0.5s; -moz-transition: all 0.5s; -o-transition: all 0.5s; -ms-transition: all 0.5s; transition: all 0.5s; padding: 0; } .headerTopMenu li.active a, .headerTopMenu li a:hover { color: #f00; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="headerTopMenu"> <ul class="nav"> <li class="active"><a href="#home">Home</a></li> <li><a href="#about">About</a></li> <li><a href="#service">Services</a></li> <li><a href="#portfolio">Portfolio</a></li> <li><a href="#blogs">Blog</a></li> <li><a href="#contact">contact</a></li> </ul> </div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM