前言
记录一下学习的笔记。参考教程:jQuery菜鸟教程;jQuery中文文档。
上一篇博客中记录了jQuery选择器,这篇文章就记录一下筛选器。
一、几种常用的筛选器
1.获取当前标签的下一个标签
$(this).next() //this代指当前标签
2.获取当前标签的上一个标签
$(this).prev() //this代指当前标签
3.获取当前标签的父标签
$(this).parent() //this代指当前标签
4.获取当前标签的孩子标签
$(this).children() //this代指当前标签
5.获取当前标签的所有兄弟标签
$(this).siblings() //this代指当前标签
6.按指定内容来查找标签
$(this).find() //this代指当前标签,按find()中的内容来查找
二、jQuery实现一个简单的左侧菜单栏
在学习JavaScript的时候,我们用JavaScript和DOM选择器实现了一个简单的左侧菜单栏的效果,在这里用jQuery实现一个相同的功能,进一步来看jQuery的强大之处:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>test3</title>
<style>
.header{
background-color: black;
color: wheat;
}
.content{
min-height: 50px;
}
.hide{
display: none;
}
</style>
</head>
<body>
<div style="height: 400px;width: 200px; border: 1px solid #dddddd">
<div class="item">
<div class="header">标题一</div>
<div class="content">内容一</div>
</div>
<div class="item">
<div class="header">标题二</div>
<div class="content hide">内容二</div>
</div>
<div class="item">
<div class="header">标题三</div>
<div class="content hide">内容三</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-1.12.4.js" integrity="sha256-Qw82+bXyGq6MydymqBxNPYTaUXXq7c8v3CwiYwLLNXU=" crossorigin="anonymous"></script>
<script>
//绑定,将所有选中的class=‘header’的都绑定上一个function函数
$(".header").click(function () {
$(this).next().removeClass('hide').parent().siblings().find('.content').addClass('hide');
})
</script>
</body>
</html>
我们只用了一行就实现了这个功能。
解释一下代码:
$(".header").click(function () {
$(this).next().removeClass('hide').parent().siblings().find('.content').addClass('hide');
})
- $(".header")选中class=‘header’的标签;
- $(".header").click(function ():让选中的标签绑定一个函数,每个标签都执行function函数;
- $(this):是指当前标签,this是DOM对象, $(this)变成jQuery对象;
- $(this).next():找到当前标签的下一个标签,也就是class=‘content’的标签;
- $(this).next().removeClass(‘hide’):将这个标签中的hide属性移除,也就是让它显示出来;
- $(this).next().removeClass(‘hide’).parent():找到它的父亲标签;
- $(this).next().removeClass(‘hide’).parent().siblings():找到父亲标签的兄弟标签,也就是其余两个div;
- $(this).next().removeClass(‘hide’).parent().siblings().find(’.content’):在所有的兄弟标签中找到class='content’的标签;
- $(this).next().removeClass(‘hide’).parent().siblings().find(’.content’).addClass(‘hide’);:将class=‘content’的标签添加一个hide属性,也就是让它隐藏。
注意:
- addClass(‘hide’):添加class=‘hide’,如果hide已经存在就不用再添加;
- removeClass(‘hide’):移除hide;
写在最后
本文是个人的一些学习笔记,如有侵权,请及时联系我进行删除,谢谢大家.