使用 jQuery 在单击时添加和删除类? [英] Add and remove a class on click using jQuery?
本文介绍了使用 jQuery 在单击时添加和删除类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
请参阅此小提琴.
我正在尝试在被点击的 li 元素上添加和删除一个类.这是一个菜单,当单击每个 li 项目时,我希望它获得该类,而所有其他 li 项目都删除了该类.所以一次只有一个 li 项目有这个类.这就是我已经走了多远(见小提琴).我不确定如何使关于链接"从当前类开始,但是当单击其他 li 项目之一时它会被删除?
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');
});
推荐答案
为什么不尝试这样的事情?
Why not try something like this?
$('#menu li a').on('click', function(){
$('#menu li a.current').removeClass('current');
$(this).addClass('current');
});
这篇关于使用 jQuery 在单击时添加和删除类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文