Heim > Fragen und Antworten > Hauptteil
判断当前元素是否有某个class,有就不添加,没有就添加当前class
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);
}