jQuery:如果单击其他元素,则删除类 [英] jQuery: Remove class if other element is clicked

查看:81
本文介绍了jQuery:如果单击其他元素,则删除类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含锂元素的ul列表.当用户单击这些li元素之一时,应将一个类添加到该li元素.

I have an ul-list that contains li-elements. When the user clicks on one of these li elements a class should be added to that element.

这很容易设置,但是,当单击另一个li元素时,我希望从非活动li中删除活动"类.

This is easy to setup, however, when the other li-element is clicked I want the "active"-class to be removed from the non-active li.

我已经解决了这个问题: http://jsfiddle.net/tGW3D/

I have made a jsfiddle of the problem: http://jsfiddle.net/tGW3D/

任何时候都应该有一个红色的锂元素.如果单击第二个,然后单击第一个,则只有第一个应为红色.

There should be one li-element that is red at any one time. If you click the second and then the first, only the first should be red.

推荐答案

这将从活动的每个li中删除活动的类,然后将其添加到被单击的Element中.

This will remove the active class from each li that have active and than will add to the Element which was clicked.

$('body').on('click', 'li', function() {
      $('li.active').removeClass('active');
      $(this).addClass('active');
});

这篇关于jQuery:如果单击其他元素,则删除类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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