使用jQuery单击添加和删除类? [英] Add and remove a class on click using jQuery?

查看:155
本文介绍了使用jQuery单击添加和删除类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请参阅小提琴

我是试图在点击的li元素上添加和删除一个类。它是一个菜单,当一个人点击每个li项目,我想要获得类和所有其他li项目已删除类。所以一次只有一个li项有类。这是我有多远(见小提琴)。我不知道如何使'about-link'从类当前开始,但然后它是删除,当其他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');
});


推荐答案

为什么不试试这样?

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

JSFiddle

这篇关于使用jQuery单击添加和删除类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆