在添加之前检查班级是否已经分配 [英] Check if class already assigned before adding

查看:85
本文介绍了在添加之前检查班级是否已经分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在jQuery中,建议在添加该类之前先检查是否已将一个类分配给某个元素吗?会不会有任何效果?

In jQuery, is it recommended to check if a class is already assigned to an element before adding that class? Will it even have any effect at all?

例如:

<label class='foo'>bar</label>

不确定是否已将类baz分配给label时,这是最好的方法:

When in doubt if class baz has already been assigned to label, would this be the best approach:

var class = 'baz';
if (!$('label').hasClass(class)) {
  $('label').addClass(class);
}

否则就足够了:

$('label').addClass('baz');

推荐答案

只需调用addClass(). jQuery将为您完成检查.如果您自己进行检查,那么您将使工作加倍,因为jQuery会仍然为您运行检查.

Just call addClass(). jQuery will do the check for you. If you check on your own, you are doubling the work, since jQuery will still run the check for you.

这篇关于在添加之前检查班级是否已经分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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