Add and remove a class on click using jQuery?

可紊 提交于 2019-11-26 03:41:15

问题


Please see this fiddle.

I am trying to add and remove a class on li elements that are clicked. It is a menu and when one clicks on each li item I want it to gain the class and all other li items have the class removed. So only one li item has the class at a time. This is how far I have got (see fiddle). I am not sure how to make the \'about-link\' start with the class current, but then it is remove when one of the other li items are clicked on?

$(\'#about-link\').addClass(\'current\');
$(\'#menu li\').on(\'click\', function() {
    $(this).addClass(\'current\').siblings().removeClass(\'current\');
});

回答1:


Why not try something like this?

$('#menu li a').on('click', function(){
    $('#menu li a.current').removeClass('current');
    $(this).addClass('current');
});

JSFiddle




回答2:


you can try this along, it may help to give a shorter code on large function.

$('#menu li a').on('click', function(){ $('li a.current').toggleClass('current'); });




回答3:


The other li elements are not siblings of the a element.

$('#menu li a').on('click', function(){
    $(this).addClass('current').parent().siblings().children().removeClass('current');
}); 



回答4:


You're applying your class to the <a> elements, which aren't siblings because they're each enclosed in an <li> element. You need to move up the tree to the parent <li> and find the ` elements in the siblings at that level.

$('#menu li a').on('click', function(){
$(this).addClass('current').parent().siblings().find('a').removeClass('current');
});

See this updated fiddle




回答5:


You can do this:-

$('#about-link').addClass('current');
$('#menu li a').on('click', function(e){
    e.preventDefault();
    $('#menu li a.current').removeClass('current');
    $(this).addClass('current');
});

Demo: Fiddle




回答6:


Try this in your Head section of the site:

$(function() {
    $('.menu_box_list li').click(function() {
        $('.menu_box_list li.active').removeClass('active');
        $(this).addClass('active');
    });
});



回答7:


Here is an article with live working demo Class Animation In JQuery

You can try this,

$(function () {
   $("#btnSubmit").click(function () {
   $("#btnClass").removeClass("btnDiv").addClass("btn");
   });
});

you can also use switchClass() method - it allows you to animate the transition of adding and removing classes at the same time.

$(function () {
        $("#btnSubmit").click(function () {
            $("#btnClass").switchClass("btn", "btnReset", 1000, "easeInOutQuad");
        });
    });



回答8:


var selector = '.classname';
$(selector).on('click', function(){
    $(selector).removeClass('classname');
    $(this).addClass('classname');
});


来源:https://stackoverflow.com/questions/19520446/add-and-remove-a-class-on-click-using-jquery

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