swap classes on click

江枫思渺然 提交于 2019-12-19 11:27:56

问题


I have a list of 6 items that are in a global div (navigationagence) Right now I am able to add a class on click but right now they adds up which means that once my six items are clicked they all end up with the currentagence class.

I want to be able to remove the add a class to the clicked item but remove it to the other, How can I achieve that? Here is the jquery code I am using right now.

$("#navigationagence ul li").click(function () { $(this).toggleClass("currentagence"); });

回答1:


You can use the siblings() method to get the other list items and remove the class from them:

$("#navigationagence ul li").click(function() {
    $(this).addClass("currentagence").siblings().removeClass("currentagence");
});



回答2:


Alternatively you can use:

$("#navigationagence ul li").click(function() {
    $(".currentagence").removeClass("currentagence");
    $(this).addClass("currentagence");
});


来源:https://stackoverflow.com/questions/5694288/swap-classes-on-click

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