通过 jquery 添加类,但仅当不存在时

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8266662/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 10:15:28  来源:igfitidea点击:

add class via jquery but only when not exists

jquerylist

提问by Mark Henry

I would like to add a class (class="bbox") to a ul-list but only if no class exists. This is what i have so far. How do I check with jquery if a class exists in the ul-tag?

我想向 ul-list 添加一个类 (class="bbox"),但前提是不存在类。这是我到目前为止。如果 ul-tag 中存在类,如何使用 jquery 检查?

$("ul").addClass("bbox");

回答by Matt Asbury

If you want to check if a specific class exists then:

如果要检查特定类是否存在,则:

 if(!$("ul").hasClass("class-name")){
    $("ul").addClass("bbox");
 }

If you want to check if any class exists:

如果要检查是否存在任何类:

if ($('ul').attr('class') == '') {
    $("ul").addClass("bbox");
}

回答by Tormod Haugene

Just use $('.selector').addClass("myClass");.

只需使用$('.selector').addClass("myClass");.

The jQuery add/remove class functions both check for duplicates internally, meaning that calling addClasstwice only will add the class once.

jQuery 添加/删除类函数都在内部检查重复项,这意味着调用addClass两次只会添加一次类。

回答by aemonge

karim79 you almost got it !

karim79 你几乎明白了!

let me correct you

让我纠正你

$("ul:not([class*='bbox'])").addClass("bbox");

You match the tag with absolute no classes, and if ul had other classes the matching wouldn't be made. You got to search for the exactly class you wish to add. Like .hasClass aproach.

您将标签与绝对没有类匹配,如果 ul 有其他类,则不会进行匹配。您必须搜索要添加的确切类。像 .hasClass 方法。

hope it helps

希望能帮助到你

回答by Vishal Nair

I was wondering this would work fine -->

我想知道这会正常工作 -->

$("ul").removeClass("bbox").addClass("bbox");

$("ul").removeClass("bbox").addClass("bbox");

First it will remove if there is any and then add new one . Worked best for me as i am too lazy to type all that ifthingy.

首先它将删除(如果有),然后添加新的。对我来说效果最好,因为我懒得打字if

回答by Mahmoud

you can use this code for adding class only when if not exist

仅当不存在时,您才能使用此代码添加类

$('.your-dom:not(.class-name)').addClass('class-name');

回答by karim79

Concisely:

简而言之:

// fine, because nothing happens if 
// there are no matching elements
$("ul[class='']").addClass("bbox");

回答by Danial

If I'm toggling between 2 classes I use this method

如果我在 2 个类之间切换,我会使用这个方法

if (foo)
    $('button.btn-foo').removeClass('foo bar').addClass('foo');
if (bar)
    $('button.btn-foo').removeClass('foo bar').addClass('bar');

So I don't have to check the current setting of the button

所以我不必检查按钮的当前设置