问题描述
我正在处理一个非常标准的点击事件。
on.click:从所有列表项中删除活动类,然后将活动类添加到点击列表项。
即ie
var li = $(' .child项');
li.click('active');
});
li.click(function(){
li.removeClass('active');
li.addClass
按预期工作。但是,我还需要一个条件,即如果再次单击活动类,它将从所单击的项中删除活动类。
我试过这个:
$('。child-item ').toggle(function(e){
$('。child-item')。removeClass('active');
$(this).addClass('active') ;
},function(){
$('。child-item')。removeClass('active');
$(this).removeClass('active' );
});
但通常切换处于关闭状态,因此需要双击才能切换回来在轨道上。这似乎是一个非常简单的解决方案,但我似乎无法让它工作。
。这适用于单击相同元素时,但不会在每次单击时清除所有活动类。
更新
我得到了它的工作,但TrueBlueAussie的答案更短,更好。这是我的工作小提琴:
您的第二个点击处理程序只会在注册事件时附加到匹配的有效项目。
将此全部替换为:
$('。child-item')。click(function(function( e){
$('。child-item.active')。not(this).removeClass('active');
$(this).toggleClass('active');
});
您可以使用 not()
来排除所选事物列表中的当前项目无效,然后只需切换选定的项目。
JSFiddle:
I am working on a click event, which intially is pretty standard.
on.click: Remove the active class from all list items, then add active to the clicked list item.
ie
var li = $('.child-item');
li.click(function(){
li.removeClass('active');
li.addClass('active');
});
Works as expected. However, I also need a condition that if the active class is clicked again, it will remove the active class from the clicked item.
I tried this:
$('.child-item').toggle(function(e){
$('.child-item').removeClass('active');
$(this).addClass('active');
}, function() {
$('.child-item').removeClass('active');
$(this).removeClass('active');
});
but often the toggle is in the off state, so it requires a double click to get the toggle back on track. This seems like it would be a pretty straightforward solution, but I cannot seem to get it to work.
Added a jsFiddle here with another option. This is fine for when the same element is clicked, but it doesn't clear all active classes on each click.
Update
I got it working but TrueBlueAussie's answer is shorter and better. Here is my working fiddle:https://jsfiddle.net/v7b8cbj5/
Your second click handler will only attach to matching "active" items when the event was registered.
Replace it all with just this:
$('.child-item').click(function(e){
$('.child-item.active').not(this).removeClass('active');
$(this).toggleClass('active');
});
You can use not()
to exclude the current item from selected list of things to make inactive, then just toggle the selected one.
JSFiddle: https://jsfiddle.net/81ex7dmm/2/
这篇关于点击事件添加和删除类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!