在 jQuery 中使用“hasClass"检查添加/删除 CSS 类的更简洁方法? [英] Neater way of checking adding/removing a CSS class using 'hasClass' in jQuery?

查看:21
本文介绍了在 jQuery 中使用“hasClass"检查添加/删除 CSS 类的更简洁方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有时我想在 jQuery 中检查某种条件,然后根据结果向元素添加/删除 cssClass.

From time to time in jQuery I want to check a condition of some kind, and then based on the result add/remove a cssClass to an element.

在调用 add(remove)Class 之前,我总是检查该类是否尚未(或已)应用.

Before calling add(remove)Class, I always check to see if that class isn't (or is) applied already.

var myElement = $('#something'),
    someClass = 'coolClass';

if (someCondition) {

   // addClass, but only if that class isn't already on this element
   if (!myElement.hasClass(someClass)) { myElement.addClass(someClass); }

} else {

   // otherwise, removeClass, but only if it's already on this element
   if (myElement.hasClass(someClass)) { myElement.removeClass(someClass); }

}

有没有更简洁的写法?

我确信一定有更好的方法来做到这一点,因为嵌套的 if 语句对我来说很糟糕.

Is there a neater way of writing the above?

I'm sure there must be a nicer way of doing this, as the nested if statements smell to me.

只是一个澄清说明(在下面的答案之后添加).需要注意的是,toggleClass(className) 是不够的,因为我明确想根据条件检查删除或添加 - 并且需要考虑切换"' 不同步.(亚当在下面对罗布回答的评论中给出了一个例子).

Just a clarifying note (added after the answers below). It is important to note here than toggleClass(className) will not suffice as I explicitally want to remove or add based on a condition check - and need to account for the 'toggle' going out of sync. (Adam gives an example in a comment on Rob's answer below).

推荐答案

var myElement = $('#something'),
someClass = 'coolClass';
myElement.toggleClass(someClass, someCondition);

toggleClass 本质上是为你做检查.如果你执行一个 toggleClass('class', true),它只会在该类还没有的情况下实际将它放在那里,并且永远不会添加一个以上的同名类.

toggleClass does your check for you essentially. If you do a toggleClass('class', true) it'll only actually put that class on there if it's not already, and will never add more than one class of the same name.

这篇关于在 jQuery 中使用“hasClass"检查添加/删除 CSS 类的更简洁方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆