-->

Change background image of
  • on click of ta
  • 2020-06-29 02:54发布

    问题:

    html:

     <ul>
        <li id="Co" class="libgc" ><b>CO</b></li>
        <li id="NSCO" class="libgc active"><span> <a href="#NSale.php" target="homeFrame" class="aclass">NSale</a></span></li>
     </ul>
    

    css:

    .libgc {
    background-color: #CCC;
    padding-top: 5px;
    padding-bottom: 5px;
    text-align: center;
    background-image: url(../images/pcnav.png);
    border: 1px solid #CCC;
    }
    

    jquery:

     $("li").click(function(){
        $(this).css('background-image', 'url("images/btnSelectedTab.png")');
        $(this).css('color','black');
      });
    
     });
    

    Problem : When I click on first link its background image is changed, but again next time when I click on other link,its background is also changed, & first links background is also similar.(Meant when I click on 2nd link, 1st links image should get back to the basic once.)

    How to reset background image to the previous one,when I click on some other links.

    回答1:

    Try this

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

    CSS for the new active class is

    li.active {
       background-image: url(../images/btnSelectedTab.png);
       color: black;
    }
    


    回答2:

    Create a class for what you wish the active li tag to look like; and use the following:

    $('li').click(function(){
        $(this).addClass('active').siblings().removeClass('active');
    });
    

    This should affect only list items within the same ul tag.