【问题标题】:jquery select element which doesn't has the active classjquery 选择没有活动类的元素
【发布时间】:2011-12-14 15:27:51
【问题描述】:

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

<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');
        ...
        ...
    });

当一个元素的类处于活动状态时,我不想制作动作/动画...

我该怎么做??

【问题讨论】:

    标签: jquery jquery-selectors css-selectors


    【解决方案1】:

    您可以使用.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');
        //...
    });
    

    【讨论】:

    • 感谢它的工作。它必须是 $('.collSex a').andSelf().toggleClass('active');否则它不会切换类
    • 但这会将active 类也添加到所有其他链接...这样,它将从类active 的链接中删除它并将其添加到当前链接。
    【解决方案2】:
    $('.collSex a').click(function(){ 
        if($(this).hasClass('active'))
        ... 
        ... 
    }); 
    

    【讨论】:

      【解决方案3】:

      使用 jQuery hasClass 方法试试这个。

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

      【讨论】:

        【解决方案4】:

        也许你可以利用 not 选择器

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

        【讨论】:

        • 只有在页面加载时评估一次。类在运行时更改。
        猜你喜欢
        • 1970-01-01
        • 2011-02-07
        • 1970-01-01
        • 2020-05-21
        • 2013-07-17
        • 2010-10-24
        • 1970-01-01
        • 2017-05-19
        • 1970-01-01
        相关资源
        最近更新 更多