问题
I got following menu:
<ul id="nav" class="nav">
<li>
<a class="navitem active" href="javascript:loadTab();">My Profile </a>
</li>
<li>
<a class="navitem search" href="javascript:loadTab();"> Search </a>
</li>
<li>
<a class="navitem" href="javascript:loadTab();">Favorites </a>
</li>
</ul>
And my function (loaded in a .js file in the header):
function loadTab() {
jQuery(".navitem").removeClass("active");
jQuery(".navitem").click(function () {
jQuery(this).addClass("active");
});
}
Removing the class "active" works, adding the class "active" to the clicked element isn't working. Any ideas?
Best regards!
回答1:
As thatidiotguy said, you're removing the class in the wrong place. You want something like this:
jQuery(".navitem").click(function (event) {
event.preventDefault();
jQuery(".navitem").removeClass("active");
jQuery(this).addClass("active");
});
Edit: And also, no need for the javascript:loadTab();
in your a
tags. Change their href
attributes to #
:
<ul id="nav" class="nav">
<li>
<a class="navitem active" href="#">My Profile </a>
</li>
<li>
<a class="navitem search" href="#"> Search </a>
</li>
<li>
<a class="navitem" href="#">Favorites </a>
</li>
</ul>
Also, I added event.preventDefault();
in the click
event handler for the links.
回答2:
This is because whenever you click the tab, you are removing the class. You are then telling the tab to call loadTab, when it is clicked. This once again removes the class. Think Inception "Dream within a Dream"
来源:https://stackoverflow.com/questions/13198093/jquery-removeclass-and-addclass-within-a-function