猿问

基于当前 URL 问题的主动导航类

我有以下 HTML 菜单:


<div class="nav">

            <ul>

                <li class="first"><a href="/">Home</a></li>

                <li><a href="/something/">Something</a></li>

                <li><a href="/else/">Else</a></li>

                <li class="last"><a href="/random/">Random</a></li>

            </ul>

            <ul style="float:right;">   

                <li class="first last"><a href="/news/">News</a></li>

            </ul>

        </div>

    </div>

然后我有这个代码:


jQuery(function($){

    var current = location.pathname;

    $('.nav ul li a').each(function(){

        var $this = $(this);

        // if the current path is like this link, make it active

        if($this.attr('href').indexOf(current) !== -1){

            $this.addClass('active');

        }

    })

})

代码运行良好,但有问题。例如,如果我看到主页 (www.example.com),那么所有菜单链接都会收到活动类。另一个问题是它适用于 www.example.com/something 但如果我去 www.example.com/something/1 等,它不会保持活动状态。知道如何解决这个问题吗?提前致谢!


幕布斯6054654
浏览 132回答 3
3回答

qq_花开花谢_0

对于主页,在列表中添加额外的类“默认”。<li class="first default"><a href="/">Home</a></li>jQuery 代码。&nbsp;jQuery(function($){&nbsp; &nbsp; &nbsp; &nbsp; var current = location.pathname;&nbsp; &nbsp; &nbsp; &nbsp; console.log(current);&nbsp; &nbsp; &nbsp; &nbsp; //remove the active class from list item.&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; $('.nav ul li a').removeClass('active');&nbsp; &nbsp; &nbsp; &nbsp; if(current != '/'){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $('.nav ul li a').each(function(){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var $this = $(this);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // if the current path is like this link, make it active&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if(current.indexOf($this.attr('href')) !== -1 && $this.attr('href') != '/'){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $this.addClass('active');&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; })&nbsp; &nbsp; &nbsp; &nbsp; }else{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;console.log('home');&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $('.default a').addClass('active');&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; })

桃花长相依

使用以下 jQuery 代码添加active类:$(function() {&nbsp; &nbsp; &nbsp; var pgurl = window.location.href.substr(window.location.href&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;.lastIndexOf("/") + 1);&nbsp; &nbsp; &nbsp; $(".nav ul li a").each(function() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;if ($(this).attr("href") == pgurl || $(this).attr("href") == '')&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $(this).addClass("active");&nbsp; &nbsp; &nbsp; })&nbsp; &nbsp;});
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答