在jquery中可以使用2种方法来判断一个元素是否包含一个确定的类(class)。两种方法有着相同的功能。2种方法如下:
1. is(‘.classname’)
2. hasClass(‘classname’)
以下是一个div元素是否包含一个redColor的例子:
1. 使用is(‘.classname’)的方法
$('div').is('.redColor')
2. 使用hasClass(‘classname’)的方法(注意jquery的低版本可能是hasClass(‘.classname’))
$('div').hasClass('redColor')
以下是检测一个元素是否含有一个redColor类的例子,含有时,则把其类变为blueColor。
<!DOCTYPE html>
<html lang="en"><head> <meta charset="UTF-8"> <title>Document</title> <style type="text/css"> .redColor { background:red; } .blueColor { background:blue; } </style> <script type="text/javascript"src="jquery-1.8.1.min.js"></script></head><body> <h1>jQuery check if an element has a certain class</h1> <div class="redColor">This is a div tag with class name of "redColor"</div> <p> <button id="isTest">is('.redColor')</button> <button id="hasClassTest">hasClass('.redColor')</button> <button id="reset">reset</button> </p> <script type="text/javascript">$("#isTest").click(function () {
if($('div').is('.redColor')){ $('div').addClass('blueColor'); } });$("#hasClassTest").click(function () {
if($('div').hasClass('redColor')){ $('div').addClass('blueColor'); } }); $("#reset").click(function () { location.reload(); }); </script></body></html>