jQuery的is()方法,jqueryis方法
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
回呼函數 描述:
判斷點擊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