返回值:Boolean is(expr|obj|ele|fn)
概述
根據選擇器、DOM元素或 jQuery 對像來檢測匹配元素集合,如果其中至少有一個元素符合這個給定的表達式就返回true。
如果沒有元素符合,或者表達式無效,都返回'false'。 '''注意:'''在jQuery 1.3中才對所有表達式提供了支援。在先前版本中,如果提供了複雜的表達式,比如層級選擇器(比如 + , ~ 和 > ),始終會返回true
參數
expr String V1.0
字串值,包含供匹配目前元素集合的選擇器表達式。
jQuery object object V1.6
現有的jQuery對象,以匹配目前的元素。
element Expression V1.6
一個用於匹配元素的DOM元素。
function(index) Function V1.6
一個函式用來作為測試元素的集合。它接受一個參數index,這是元素在jQuery集合的索引。在函式, this指的是目前的DOM元素。
示例
參數expr 描述:
由於input元素的父元素是一個表單元素,所以返回true。
HTML 程式碼:
<form><input type="checkbox" /></form>
jQuery 程式碼:
$("input[type='checkbox']").parent().is("form")
結果:
true
回撥函式 描述:
判斷點選li標籤增加背景色為紅色,如果點選的是第2個strong,目前的li增加背景色為綠色,
HTML 程式碼:
<ul>
<li>
<strong>
list</strong>
item 1 - one strong tag</li>
<li>
<strong>list</strong> item <strong>2</strong> - two <span>strong tags</span></li>
<li>list item 3</li>
</ul>
jQuery 程式碼:
$("li").click(function() {
var $li = $(this),
isWithTwo = $li.is(function() {
return $('strong', this).length === 2;
});
if ( isWithTwo ) {
$li.css("background-color", "green");
} else {
$li.css("background-color", "red");
}
});
結果:
-
list
item 1 - one strong tag
-
list
item
2
- two
strong tags
-
list item 3
-
list item 4
-
list item 5