Bootstrap menu change li active class on click

前端 未结 6 1517
予麋鹿
予麋鹿 2021-02-05 09:12

I have the following menu by bootstrap

HTML

相关标签:
6条回答
  • 2021-02-05 09:30

    UPDATED

    Your css selectors seems to be wrong. Please try as given below,

    <script>
        $(".nav li").on("click", function() {
          $(".nav li").removeClass("active");
          $(this).addClass("active");
        });
    
    </script>
    

    I have created a plunkr for this here

    0 讨论(0)
  • 2021-02-05 09:37

    one of your selectors is malformed, by looking at your html it looks like on the third line of the script that selector isn't doing what I think you want it to.

    $("#homeL, #workL").click(function(){
    
      //$(".nav navbar-nav li") <-this is looking for a <li> inside a <navbar-nav>  
      // tag inside a tag with the class "nav"
    
      $(".nav.navbar-nav li").removeClass("active");
      $(this).addClass("active");
    });
    
    0 讨论(0)
  • 2021-02-05 09:40

    Include this script

        <script type="text/javascript">
        $(function(){
            $('.nav a').filter(function(){
                return this.href==location.href}).parent().addClass('active').siblings().removeClass('active');
    
            $('.nav a').click(function(){
                $(this).parent().addClass('active').siblings().removeClass('active')    
                });
            });
    </script>
    
    0 讨论(0)
  • 2021-02-05 09:47

    Try this:

    $("ul li").on("click", function() {
        $("li").removeClass("active");
        $(this).addClass("active");
      });
    

    You will have to play around with it with your given tags. What helped me was declaring this to become active, then removing the active class.

    0 讨论(0)
  • 2021-02-05 09:47

    i found another workaround for this which is very easy to use.

      <div class="navbar-collapse collapse">
         <ul class="nav navbar-nav">
           <li class="<?php if($page=="home.html"){echo "active";} ?>"> id="homeL"><a data-scroll href="home.html">Home</a></li>
           <li class="<?php if($page=="about.html"){echo "active";} ?>"><a href="about.html">About</a></li>
           <li class="<?php if($page=="work.html"){echo "active";} ?>"> id="workL"><a data-scroll href="work.html">Work</a></li>
           <li class="<?php if($page=="contact.html"){echo "active";} ?>"><a href="contact.html">Contact</a></li>
        </ul>
      </div>
    
    0 讨论(0)
  • 2021-02-05 09:56
        $(".ul li").on("click", function() {
            $(this).siblings().removeClass('active');
            $(this).addClass("active");
        });
    

    This is the solution that worked for me. I declared this to become active and remove the active class and also adding the .siblings() method that allows you to search for the siblings of the li elements in the document.

    0 讨论(0)
提交回复
热议问题