2011-12-14 64 views
1

我想在用户点击一个元素时制作一个动画。除非元素具有“活动”类。jquery select元素没有活动类

<div class="collectionContainer"> 
      <div class="collectionName">SPRING SUMMER <br> 2012</div> 
      <div class="collSex"><a href="#" id="collection1-man" class="active"> MAN </a></div> 
      <div class="collSex"><a href="#" id="collection1-woman"> WOMAN </a></div> 
     </div> 

我jQuery代码

$('.collSex a').click(function(){ 
     $('.collSex a').removeClass('active'); 
     $(this).addClass('active'); 
     ... 
     ... 
    }); 

当一个元素有类活动的,我不想让动作/动画...

我应该怎么办呢?

回答

3

可以使用.hasClass[docs]方法:

$('.collSex a').click(function(){ 
    if(!$(this).hasClass('active')) 
     $('.collSex a.active').andSelf().toggleClass('active'); 
     //... 
    } 
}); 

或使用事件委派:

$('.collSex').on('click', 'a.active', function() { 
    $('.collSex a.active').andSelf().toggleClass('active'); 
    //... 
}); 
+0

感谢它的工作。它必须是 $('。collSex a')。andSelf()。toggleClass('active'); 否则它不会切换类 – peterK 2011-12-14 15:39:52

+0

但是,这样会将“active”类添加到所有其他链接......这样,它将从类active的链接中删除它并将其添加到当前链接。 – 2011-12-14 15:40:50

2
$('.collSex a').click(function(){ 
    if($(this).hasClass('active')) 
    ... 
    ... 
}); 
1

试试这个使用jQuery hasClass方法。

$('.collSex a').click(function(){ 
    if(!$(this).hasClass('active')) 
    { 
     //Your code here. 
    } 
}); 
1

也许你可以采取选择的优势

$('collsex a:not(.active)').click(function(){ ....};