如何使用jquery判斷一個元素是否含有一個指定的類(class)
一、總結
一句話總結:可以用hasClass方法(專用)和is方法
1、is(expr|obj|ele|fn)的方法幾個參數表示什么?
參數可以是表達式,可以是jquery對象,可以是元素,可以是函數
2、hasClass()和is()的關系是什么?
hasclass()
檢查當前的元素是否含有某個特定的類,如果有,則返回true。
這其實就是 is("." + class)。
二、使用jquery判斷一個元素是否含有一個指定的類(class)
在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。
<html>
<head>
<styletype="text/css">
.redColor {
background:red;
}
.blueColor {
background:blue;
}
</style>
<scripttype="text/javascript"src="jquery-1.3.2.min.js"></script>
</head>
<body>
<h1>jQuery check if an element has a certain class</h1>
<divclass="redColor">This is a div tag with class name of "redColor"</div>
<p>
<buttonid="isTest">is('.redColor')</button>
<buttonid="hasClassTest">hasClass('.redColor')</button>
<buttonid="reset">reset</button>
</p>
<scripttype="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>
初始效果:

點擊is('.redColor')后的效果:

點擊hasClass('redColor')的效果與點擊is('.redColor')后的效果相同,點擊reset的效果與初始效果相同。
https://blog.csdn.net/sunqian_happy/article/details/54409531
三、jquery的hasclass()和is()簡介
1、hasclass()
檢查當前的元素是否含有某個特定的類,如果有,則返回true。
這其實就是 is("." + class)。
描述:
給包含有某個類的元素進行一個動畫。
HTML 代碼:
<div class="protected"></div><div></div>
jQuery 代碼:
$("div").click(function(){
if ( $(this).hasClass("protected") )
$(this)
.animate({ left: -10 })
.animate({ left: 10 })
.animate({ left: -10 })
.animate({ left: 10 })
.animate({ left: 0 });
});
2、is()
is(expr|obj|ele|fn)
根據選擇器、DOM元素或 jQuery 對象來檢測匹配元素集合,如果其中至少有一個元素符合這個給定的表達式就返回true。
如果沒有元素符合,或者表達式無效,都返回'false'。 '''注意:'''在jQuery 1.3中才對所有表達式提供了支持。在先前版本中,如果提供了復雜的表達式,比如層級選擇器(比如 + , ~ 和 > ),始終會返回true
exprStringV1.0
字符串值,包含供匹配當前元素集合的選擇器表達式。
jQuery objectobjectV1.6
現有的jQuery對象,以匹配當前的元素。
elementExpressionV1.6
一個用於匹配元素的DOM元素。
function(index)FunctionV1.6
一個函數用來作為測試元素的集合。它接受一個參數index,這是元素在jQuery集合的索引。在函數, this指的是當前的DOM元素。
參數expr 描述:
由於input元素的父元素是一個表單元素,所以返回true。
HTML 代碼:
<form><input type="checkbox" /></form>
jQuery 代碼:
$("input[type='checkbox']").parent().is("form")
結果:
true
