I have a html as sidebar, and 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 to do some thing:
When I click
a link such as Link 3, the page content
will change to Link 3's content, and the Link 3 will have class active
, and remove the active clss in Link 1.
I think this can be implemented in jQuery
, and I have searched many question in SO, such as:
I use this 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 most of them use preventDefault
, this will prevent the continued action. So it can't change to Link 3's page content.
If I remove the preventDefault statement, when the page load Link 3's content, the active class will back to Link 1.
So Is there any way to solve this problem?
You are binding you click on the wrong element, you should bind it to the a
.
You are prevent default event to occur on the li
, but 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();
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With