jQuery: Remove class if other element is clicked

2020-02-16 20:14发布

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.

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.

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.

8条回答
Deceive 欺骗
2楼-- · 2020-02-16 20:49

Something like this?

http://jsfiddle.net/c7ZE4/

You can use the siblings function. addClass returns the same jquery object $(this) so you can chain the siblings method which returns all the other elements except $(this).

 $('li').click(function() {
  $(this).addClass('active').siblings().removeClass('active');
 });
查看更多
Animai°情兽
3楼-- · 2020-02-16 20:54
$('li').click(function() {
  $(this).siblings().removeClass('active');
  $(this).addClass('active');
});

Check: http://jsfiddle.net/tGW3D/2/

查看更多
登录 后发表回答