.hasClass()
返回: Boolean
.hasClass( className )
描述:确定匹配元素中是否有一些元素带有指定样式类。
元素可能被分配了不止一个样式类。在HTML中,这可以用空格来隔开类名:
<div id="mydiv" class="foo bar"></div>
如果该样式类被分配到一个元素,.hasClass()
方法将返回true,哪怕别的样式类也存在。举个例子,给定上面的HTML,下面的代码将返回true:
$( "#mydiv" ).hasClass( "foo" )
将会成:
$( "#mydiv" ).hasClass( "bar" )
与此同时,这个返回false
$( "#mydiv" ).hasClass( "quux" )
示例
查找包含了“selected”样式类的段落文本。
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>hasClass demo</title> <style> p { margin: 8px; font-size: 16px; } .selected { color: red; } </style> <script src="https://code.jquery.com/jquery-1.10.2.js"></script> </head> <body> <p>This paragraph is black and is the first paragraph.</p> <p class="selected">This paragraph is red and is the second paragraph.</p> <div id="result1">First paragraph has selected class: </div> <div id="result2">Second paragraph has selected class: </div> <div id="result3">At least one paragraph has selected class: </div> <script> $( "#result1" ).append( $( "p:first" ).hasClass( "selected" ).toString() ); $( "#result2" ).append( $( "p:last" ).hasClass( "selected" ).toString() ); $( "#result3" ).append( $( "p" ).hasClass( "selected" ).toString() ) ; </script> </body> </html>
演示结果