确定元素是否具有带jQuery的CSS类 [英] Determine if an element has a CSS class with jQuery

查看:81
本文介绍了确定元素是否具有带jQuery的CSS类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用jQuery和寻找是否有一个简单的方法来确定元素是否有一个特定的CSS类与其相关联。

I'm working with jQuery and looking to see if there is an easy way to determine if the element has a specific CSS class associated with it.

我有元素的id和我正在寻找的CSS类。我只需要能够在一个if语句中,根据该元素上存在的类进行比较。

I have the id of the element, and the CSS class that I'm looking for. I just need to be able to, in an if statement, do a comparison based on the existence of that class on the element.

推荐答案

p>使用 hasClass 方法:

jQueryCollection.hasClass(className);

$(selector).hasClass(className);

参数是(很明显)一个字符串,表示您正在检查的类,并返回一个布尔所以它不支持链接像大多数jQuery方法)

The argument is (obviously) a string representing the class you are checking, and it returns a boolean (so it doesn't support chaining like most jQuery methods).

注意如果你传递 className 参数包含空格,它将与字符串集合的元素 className 字符串匹配。例如,如果您有一个元素,

Note: If you pass a className argument that contains whitespace, it will be matched literally against the collection's elements' className string. So if, for instance, you have an element,

<span class="foo bar" />

那么这将返回 true



then this will return true:

$('span').hasClass('foo bar')

,这些将返回 false

$('span').hasClass('bar foo')
$('span').hasClass('foo  bar')

这篇关于确定元素是否具有带jQuery的CSS类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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