jQuery removeClass and addClass within a function

别等时光非礼了梦想. 提交于 2019-12-24 09:13:04

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!