如何在jQuery中使用is()函数
时间:2020-02-23 14:46:02 来源:igfitidea点击:
在本文中,我们将讨论如何使用jQueryis()方法。
这是在事件处理程序之类的回调函数中经常使用的重要过滤方法。
jQuery is()
我们使用jQuery is()与另一个元素,选择器或者任何jQuery对象一起检查选定的元素。
此方法遍历DOM元素以找到匹配项,该匹配项满足传递的参数。
如果存在匹配项,它将返回true,否则返回false。
这是使用is()的一般语法;
- selector.is(filter)
过滤器可以是字符串选择器表达式,函数,元素或者任何现有的jQuery对象。
jQuery is()示例
下面的示例演示jQuery is()方法的用法。
<!doctype html>
<html>
<head>
<title>jQuery traversing is() example</title>
<style>
div {
width: 60px;
height: 60px;
margin: 5px;
float: left;
border: 4px ;
background: green;
text-align: center;
font-weight: bolder;
cursor: pointer;
}
.blue {
background: blue;
}
.red {
background: red;
}
.grey{
background: grey;
}
span {
color: white;
font-size: 16px;
}
p {
color: red;
font-weight: bolder;
background: yellow;
margin: 3px;
clear: left;
display: none;
}
</style>
<script src="https://code.jquery.com/jquery-2.1.1.js"></script>
</head>
<body>
<h2>Click on each div </h2>
<div id="sachin">Sachin</div>
<div class="blue">Ganguly</div>
<div>Dravid</div>
<div class="red">Srinath</div>
<div class="grey">Kumble</div>
<div>Sanju</div>
<p> </p>
<script>
$( "div" ).on( "click", function() {
if ( $( this ).is( "#sachin" ) ) {
$( "p" ).text( "Best Batsman in the world" );
}
else if ( $( this ).is( ".blue" ) ) {
$( "p" ).text( "Best Captain Ever" );
}
else if ( $( this ).is( ":contains('Dravid')" ) ) {
$( "p" ).text( "The Wall" );
}
else if ( $( this ).is( ".red,.grey" ) ) {
$( "p" ).html( "Clicked on Srinath or Kumble : From Karnataka" );
}
else {
$( "p" ).html( "Young Talent" );
}
$( "p" ).hide().slideDown( "slow" );
$( this ).addClass("yellow");
});
</script>
</body>
</html>
在此示例中,您可以看到is()方法的用法。
$(this).is(" #sachin")":其中is()方法检查所选元素的id =" sachin""。
$(this).is(" .blue"):is()检查所选元素是否属于"class =" blue""。
$(this).is(":contains('Dravid')")":这里is()检查元素是否包含字符串" Dravid"。
$(this).is(" .red,.grey")":这行代码检查所选元素是属于class =" red"还是class =" blue"。
Srinath和Kumble的输出相同。
如果通过以上任何条件,并在div元素下方显示具有滑动效果的输出文本,则返回true。
否则执行默认条件。
在我们的例子中,单击" Sanju"时将执行默认条件。
您可以尝试将函数,jQuery对象或者任何元素传递给jQuery is()方法。

