在查看去年学习的一些东西时,看到当时学习jquery有用到is这个知识点,但是如今我已经早忘光了,乘此机会,复习一下。
定义和用法
$(selector).is(selectorElement,function(index,element))
参数 | 描述 |
selectorElement | 必须。选择器表达式,根据选择器/元素/jQuery 对象检查匹配元素集合,如果存在至少一个匹配元素,则返回 true,否则返回 false |
function(index,element) | 可选。指定了选择元素组要执行的函数。
|
is() 根据选择器、元素或 jQuery 对象来检测匹配元素集合,如果这些元素中至少有一个元素匹配给定的参数,则返回 true。
这话很官方,根据例子,记住is的用法和参数一般是两种:第一种是传入选择器表达式,直接判断某元素/某系列元素是否为参数类型,如div,form,只要有一个为true,则返回true;第二种传入一个回调函数,某元素/某系列元素传入遍历运行该回调,并返回结果true或false,这种用法 类似于map遍历,不过map的调用是数组,is调用可以是元素。
注意:jquery中使用的选择器,可以试早期通用的css选择器,也可以是jquery拓展的选择器,如。
css通用选择器:id,标签,p:first-of-type,p:nth-child(2),p:last-child,p:nth-of-type(even)
jquery拓展选择器:$("p:first"),$("tr:even"),$("ul li:eq(3)"),$("input:not(:empty)"),$("ul li:gt(3)")
所以,css中是没有直接使用first和even,odd的伪类选择器的,只有jquery中才有。
第一种用法:元素选择器匹配
简单例子:
<form><p><input type="checkbox" />CHECKBOX</p></form>
<div>123</div>
<script>
let isFormParent = $(input[type == "checkbox"]).parent().is("form");
documents.write(isFormParent); //false
</script>
判断为checkbox的input标签的父级元素是否为“form”标签。
复杂点例子:
<div class="box">
<ul>
<li>LIST <strong>STRONG</strong> <span>SPAN</span> <strong>STRONG</strong> </li>
<li>LIST <span>SPAN</span> <strong>STRONG</strong> <strong>STRONG</strong> </li>
<li>LIST <p>P</p> <span>SPAN</span> </li>
<li>LIST <strong>STRONG</strong> <strong>STRONG</strong> </li>
</ul>
</div>
.box {
width: 300px;
}
.box ul {
list-style: none;
/* text-align: center; */
}
.box li {
border: solid 1px blue;
}
.box li > * {
background-color: green;
color: white;
}
.bg {
background-color: gray;
}
<script>
$(".box ul").bind("click",function(event){
let $target = $(event.target); //获取事件源
if($target.is("li")) {
console.log("click li!!");
$target.toggleClass("bg");
}
});
</script>
判断点击事件来源是否为“li”标签本身,是才执行操作。
第二种用法:元素遍历执行回调函数
<div class="box">
<ul>
<li><button>BUTTON</button> LIST <strong>STRONG</strong> <strong>STRONG</strong> <span>SPAN</span> <strong>STRONG</strong> </li>
<li><button>BUTTON</button> LIST <span>SPAN</span> <strong>STRONG</strong> <strong>STRONG</strong> </li>
<li><button>BUTTON</button> LIST <p>P</p> <span>SPAN</span> </li>
<li><button>BUTTON</button> LIST <strong>STRONG</strong> <strong>STRONG</strong> <strong>STRONG</strong> </li>
</ul>
</div>
$(".box ul button").bind("click",function() {
let count = $(this).parent().find("strong").length;
console.log(count);
let count2 = $(this).parent().is(function(index,element) {
return $("strong",this).length == 2;
})
console.log(count2);
})
注意$("strong",this).length 是由 $("strong")标签选择器变来的,this是指明查找的作用域
重点是js中count,count2的结果,
count是通过button的父节点找到li标签,在通过find遍历子节点中strong的个数
count2是通过is的回调函数,函数返回值只有true或false,不能返回其它。
比较下结果: