jQuery is()方法 用于检查当前元素与另一个元素、jQuery 对象或选择器是否匹配。

如果至少有一个匹配,则该方法返回 true;否则返回 false。

语法

$(selector).is(selectorElement,function(index,element))

参数

selectorElement - 必填参数。它可以是元素、jQuery 对象或匹配元素的选择器表达式。

function(index,element) - 可选参数。它是一个函数,可以用作对集合中每个元素的测试。它针对一组选定元素运行。它有两个参数定义如下

  • index:     是元素的索引位置。
  • element: 它是当前的 DOM 元素。我们可以使用同样引用当前 DOM 元素的 this 选择器。

例子

例1

<html>
<head>
<title> jQuery is() 方法 </title>
<script src = "https://code.jquery.com/jquery-3.5.1.min.js"> </script>

<script>
$(document).ready(function() {
$("span").click(function () {
	if ($(this).is("#s1")) {
		$("#s1").text("This is first span element").css({"background-color": "yellow", "font-size": "20px"});
	} else if ($(this).is("#s2")) {
		$("#s2").text("This is second span element").css({"background-color": "orange", "font-size": "20px"});
	} else {
    	        $("#s3").text("This is third span element").css({"background-color": "lightblue", "font-size": "20px"});
	}
});
});
</script>
</head>

<body>
<h2> 这是一个使用 jQuery is() 方法的例子。 </h2>
<h3> 单击以下 span 元素查看效果。 </h3>
<span id = "s1"> 点击看看 </span> <br>
<span id = "s2"> 点击看看 </span> <br>
<span id = "s3"> 点击看看 </span> <br>

</body>
</html>

例2

<html>
<head>
<title> jQuery is() 方法 </title>
<script src = "https://code.jquery.com/jquery-3.5.1.min.js"> </script>

<script>
$(document).ready(function() {
	$("span").click(function() {
		if ($("p").children().is("span")) {
			alert("span 是 p 的子元素");
		}
	});
});
</script>
</head>

<body>
<h2> 这是一个使用 jQuery is() 方法的例子。 </h2>
<h3> 单击下面的 span 元素查看效果。 </h3>
<p style = "border:2px red;">
<span> 点击我 </span>
</p>
</body>

</html>