jquery add remove class onclick

时间秒杀一切 提交于 2019-12-31 09:05:01

问题


i have any navigation menu !

   <div class="nav">
    <ul class="navigation">
    <li class="selected"><a href="#">HOME</a></li>
    <li><a href="#">PROFILE></a></li>
    <li><a href="#">CONTACTUS</a></li>
    <li><a href="#">ABOATUS</a></li>
    </ul>
    </div>

Now how to add selected class after click to any ( profile, Contactus, aboutus ) and remove selected home using Jquery.

Thanks


回答1:


On the assumption that you want to have only one element of class-name selected I suggest:

$('ul.navigation li a').click(
    function(e) {
        e.preventDefault(); // prevent the default action
        e.stopPropagation(); // stop the click from bubbling
        $(this).closest('ul').find('.selected').removeClass('selected');
        $(this).parent().addClass('selected');
    });

JS Fiddle demo.




回答2:


you can use toggleClass:

$("#myElement1").click(function(){
   $("#myElement2").toggleClass("myClass");
});



回答3:


$("a").click(function()
{
  $("a").parent().removeClass("selected");

  $(this).parent().addClass("selected");
});

Live Demo



来源:https://stackoverflow.com/questions/7138021/jquery-add-remove-class-onclick

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