.is()
描述: 判断当前匹配的元素集合中的元素,是否为一个选择器,DOM元素,或者jQuery对象,如果这些元素至少一个匹配给定的参数,那么返回true
。
-
.is( selector )
-
selector类型: Selector一个字符串,包含一个用来匹配元素的选择器表达式。
-
-
.is( function(index) )
-
function(index)类型: Function()一个函数,用来测试集合中的元素。它接受一个参数,
index
,这是元素在jQuery集合的索引位置。在函数中,this
指的是当前的DOM元素。
-
-
.is( jQuery object )
-
jQuery object类型: Object现有的jQuery对象,以匹配当前的元素。
-
-
.is( element )
-
element类型: Element个用于匹配元素的DOM元素。
-
.is()
并不创建一个新的jQuery对象。相反,它允许我们检测jQuery对象的内容,而无需修改该对象。通常在回调函数内使用该方法,例如事件处理。
例子:
Example: 显示的 is()可用于在一个事件处理程序的几种方法。
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>无标题文档</title>
<script src="jquery-1.10.2.js"></script>
<style>
div { width:60px; height:60px; margin:5px; float:left; border:4px outset; background:green; text-align:center; font-weight:bolder; cursor:pointer; }
.blue { background:blue; }
.red { background:red; }
span { color:white; font-size:16px; }
p { color:red; font-weight:bolder; background:yellow; margin:3px; clear:left; display:none; }
</style>
</head>
<body>
<div></div>
<div class="blue"></div>
<div></div>
<div class="red"></div>
<div><br/><span>Peter</span></div>
<div class="blue"></div>
<p> </p>
<script>
$("div").one("click",function(){
if($(this).is(":first-child")){
$("p").text("这是第一个div");
}else if($(this).is(".blue,.red")){
$("p").text("这是个蓝色或红色div");
}else if($(this).is(":contains('Peter')")){
$("p").text("这是Peter");
}else{
$("p").html("It's nothing <em>special</em>.");
}
$("p").hide().slideDown("slow");
$(this).css({"border-style":"inset",cursor:"default"});
});
</script>
</body>
</html>
效果图:
Example: 返回true,因为input的父级是一个表单的元素。
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>无标题文档</title>
<script src="jquery-1.10.2.js"></script>
</head>
<body>
<style>div { color:red; }</style>
<form><input type="checkbox" /></form>
<div></div>
<script>
var isFormParent = $("input[type='checkbox']").parent().is("form");
$("div").text("isFormParent = " + isFormParent);
</script>
</body>
</html>
效果图:
Example: 返回false,因为input的父级是一个P元素。
<!DOCTYPE html>
<html>
<head>
<style>div { color:red; }</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<form><p><input type="checkbox" /></p></form>
<div></div>
<script>
var isFormParent = $("input[type='checkbox']").parent().is("form");
$("div").text("isFormParent = " + isFormParent);
</script>
</body>
</html>
效果图:
Example: 针对检查列表元素交替现有的集合。 Blue, alternating list elements slide up while others turn red.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>无标题文档</title>
<script src="jquery-1.10.2.js"></script>
</head>
<body>
<style>li { cursor:pointer; }</style>
<ul id="browsers">
<li>Chrome</li>
<li>Safari</li>
<li>Firefox</li>
<li>Opera</li>
</ul>
<script>
var $alt = $("#browsers li:nth-child(2n)").css("background","#00ffff");
$("li").click(function(){
var $li = $(this);
if($li.is($alt)){
$li.slideUp();
}else{
$li.css("background","yellow");
}
})
</script>
</body>
</html>
效果图: