suchen

Heim  >  Fragen und Antworten  >  Hauptteil

javascript - 怎么判断当前是否有某个class,如果没有则添加class?

判断当前元素是否有某个class,有就不添加,没有就添加当前class

ringa_leeringa_lee2818 Tage vor1420

Antworte allen(12)Ich werde antworten

  • PHPz

    PHPz2017-04-10 16:26:02

    请使用hasClass

    Antwort
    0
  • ringa_lee

    ringa_lee2017-04-10 16:26:02

    结合上面总结了一下,我想出来的只有这几种:

    function addClass0(targetEle, filterClassName){
        var target = document.getElementById(targetEle);
        var isExist = target && target.className.split('').indexOf(filterClassName)!=-1;
        if(!isExist){
            target.className = target.className + ' ' + filterClassName;
        }
    }
    
    function addClass(targetEle, filterClassName){
        var target = document.getElementById(targetEle);
        if(!target.classList.contains('add')){
             target.classList.add('add');
        }
    }
    
    function addClass1(targetEle, filterClassName){
         if(!$(targetEle).is('.'+filterClassName)){
             $(targetEle).addClass(filterClassName);
         }
    }
    
    function addClass2(targetEle, filterClassName){
         if(!$(targetEle).hasClass(filterClassName)){
              $(targetEle).addClass(filterClassName);
         }
    }
    
    function addClass3(targetEle, filterClassName){
         $(targetEle).not('.'+filterClassName).addClass(filterClassName);
    }
    
    function addClass4(targetEle, filterClassName){
         $(targetEle+':not(.'+filterClassName+')').addClass(filterClassName);
    }
    
    function addClass5(targetEle, filterClassName){
        $(targetEle).toggleClass(filterClassName);
    }

    Antwort
    0
  • StornierenAntwort