I am trying to add active class by using JS but seems not working.
Here is the code
<ul id="menuList">
<li class="menu">
<a href="home">Home</a>
</li>
<ul id="hm">
<li>
<a href="#">home01</a>
</li>
</ul>
<li class="menu">
<a href="gallery">gallery</a>
</li>
<li class="menu">
<a href="about">about</a>
</li>
<li class="menu">
<a href="contact">contact</a>
</li>
</ul>
Updated: Try this
var flag = 1; $(document).ready(function(){ $('#menuList li:not(:first-child)').click(function(){ $('li').removeClass("active"); $(this).addClass("active"); $('#hm').css("display", "none"); $('#hm').css("list-style", "none"); flag = 1; }); $('#menuList > li:first-child').click(function(){ $('li').removeClass("active"); $(this).addClass("active"); if(flag == 1){ $('#hm').css("display", "block"); $('#hm').css("list-style", "square"); flag = 0; } else { $('#hm').css("display", "none"); $('#hm').css("list-style", "none"); flag = 1; } }); });
.active { display:block; background-color:green; } #hm{ display: none; list-style: none; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ul id="menuList"> <li class="menu active"><a href="#home">Home</a></li> <ul id="hm"> <li><a href="#">home01</a></li> </ul> <li class="menu"><a href="#gallery">gallery</a></li> <li class="menu"><a href="#about">about</a></li> <li class="menu"><a href="#contact">contact</a></li> </ul>
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.