javascript - How to change active class while click to another link in bootstrap use jquery? -
i have html sidebar, , use bootstrap
.
<ul class="nav nav-list"> <li class="active"><a href="/">link 1</a></li> <li><a href="/link2">link 2</a></li> <li><a href="/link3">link 3</a></li> </ul>
i want thing:
when click
link such link 3, page content
change link 3's content, , link 3 have class active
, , remove active clss in link 1.
i think can implemented in jquery
, , have searched many question in so, such as:
i use script:
$(document).ready(function () { $('.nav li').click(function(e) { $('.nav li').removeclass('active'); var $this = $(this); if (!$this.hasclass('active')) { $this.addclass('active'); } //e.preventdefault(); }); });
but of them use preventdefault
, prevent continued action. can't change link 3's page content.
if remove preventdefault statement, when page load link 3's content, active class link 1.
so there way solve problem?
you binding click on wrong element, should bind a
.
you prevent default event occur on li
, li
have no default behavior, a
does.
try this:
$(document).ready(function () { $('.nav li a').click(function(e) { $('.nav li.active').removeclass('active'); var $parent = $(this).parent(); $parent.addclass('active'); e.preventdefault(); }); });
Comments
Post a Comment