当我单击没有任何class =“ active”的“ li”时,我希望jquery在空的<li>
上添加一个类,并将其从另一个“ li”中删除
我有以下代码:
$("li").click(function() {
// If this isn't already active
if (!$(this).hasClass("active")) {
// Remove the class from anything that is active
$("li.active").removeClass("active");
// And make this active
$(this).addClass("active");
}
});
.active {
background-color: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<nav class="navbar navbar-default navbar-static-top">
<div class="container-fluid">
<div id="navbar2" class="navbar-collapse collapse">
<ul class="nav navbar-nav navbar-right">
<li class="active" style="font-family:Merriweather;"><a href="Default.aspx">Home</a></li>
<li class="menu" style="font-family:Merriweather;"><a href="advertize.aspx">Advertise</a></li>
<li class="dropdown" style="font-family:Merriweather;">
<a href="exhibition.aspx" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">Exhibitions <span class="caret"></span></a>
<ul class="dropdown-menu" role="menu">
<li style="font-family:Merriweather;"><a href="dubaiexhibitions.aspx">Trade fairs in U.A.E</a></li>
<li style="font-family:Merriweather;"><a href="exhibition.aspx">Trade fairs worldwide</a></li>
<li style="font-family:Merriweather;"><a href="addexhibition.aspx">Add Your Event</a></li>
</ul>
</li>
<li style="font-family:Merriweather;"><a href="subscribe.aspx">Subscribe</a></li>
<li style="font-family:Merriweather;"><a href="member_benefits.aspx">Memberships</a></li>
<li style="font-family:Merriweather;"><a href="aboutus.aspx">About us</a></li>
<li style="font-family:Merriweather;"><a href="news.aspx">News</a></li>
<li style="font-family:Merriweather;"><a href="contactus.aspx">Contact us</a></li>
<li style="font-family:Merriweather;"><a href="media_partners.aspx">Partners</a></li>
<li style="font-family:Merriweather;"><a href="login.aspx"><span class="glyphicon glyphicon-log-in"></span> Login</a></li>
</ul>
<a href="addlisting.aspx" target="_blank" class="floatingbanner"></a>
</div>
<!--/.nav-collapse -->
</div>
</nav>
我尝试了上面的代码,但是没有用。
答案 0 :(得分:1)
正如下面的评论,您的代码似乎正常工作。但是我建议您简化代码以提高效率。
如果单击了目标,<li>
必须变为<li class="active">
,然后从其他class="active"
元素中删除<li>
,则不必检查它是否当前处于活动状态。您可以简单地做到这一点:
$("li").click(function() {
$(this).addClass('active').siblings().removeClass('active');
});