第1章 jQuery介绍
1.1 什么是jQuery
jQuery是一个轻量级的、兼容多浏览器的JavaScript库,它使用户能够更方便地处理HTML Document、Events、实现动画效果、方便地进行Ajax交互,能够极大地简化JavaScript编程。
1.2 获取jQuery
下载链接:https://jquery.com/download/
1.3 jQuery使用方法
先导入jQuery再使用:
<script src="jquery-3.3.1.min.js"></script> // 一定要在使用前导入jquery文件,否则无法识别 <script>JS操作</script>
第2章 jQuery基础
2.1 jQuery对象
jQuery对象就是通过jQuery包装DOM对象后产生的对象,如果一个对象是 jQuery对象,那么它就可以使用jQuery里的方法,例如:
$(“#i1”).html() // 相当于document.getElementById("i1").innerHTML;
虽然 jQuery对象是包装 DOM对象后产生的,但是 jQuery对象无法使用 DOM对象的任何方法,同理 DOM对象也没不能使用 jQuery里的方法。
Tips:一个约定,我们在声明一个jQuery对象变量的时候在变量名前面加上$:
var $variable = // jQuery对像
var variable = // DOM对象
$variable[0] // jQuery对象转成DOM对象
2.1.1 HTML对象和jQuery对象的区别
- jQuery对象转换成DOM对象:用索引取出具体的标签
- DOM对象转换成jQuery对象:$(DOM对象)
Tips:jQuery对象保存到变量的时候,变量名要加 $ 前缀,如:var $pEle = $(“#p3”)
2.2 jQuery基础语法
$(selector).action()
2.3 查找标签
2.3.1 基本选择器
- id选择器:
// $("ID值") $("#id")
- 标签选择器:
// $("标签名") $("tagName")
- class选择器:
// $(".class名") $(".className")
- 配合使用:
// 找到有c1 class类的div标签,注意中间不要加空格 $("div.c1")
- 组合选择器:
// $("条件1,条件2") $("#id, .className, tagName")
- 所有元素选择器:
$("*")
2.3.2 层级选择器:
x和y可以为任意选择器:
$("x y"); // x的所有后代y(子子孙孙) $("x > y"); // x的所有儿子y(儿子) $("x + y") // 找到所有紧挨在x后面的y $("x ~ y") // x之后所有的兄弟y
2.3.3 基本筛选器:
:first // 第一个 :last // 最后一个 :eq(index) // 索引等于index的那个元素,从 0 开始 :even // 匹配所有索引值为偶数的元素,从 0 开始计数 :odd // 匹配所有索引值为奇数的元素,从 0 开始计数 :gt(index) // 匹配所有大于给定索引值的元素 :lt(index) // 匹配所有小于给定索引值的元素 :not(元素选择器) // 移除所有满足not条件的标签 :has(元素选择器) // 选取所有包含一个或多个标签在其内的标签(指的是从后代元素找)
【示例】:
$("ul li:first"); // 第一个 $("ul li:last"); // 最后一个(第五个) $("ul li:eq(3)"); // 第三个 $("ul li:eq(-2)"); // 倒数第二个(第四个) $("ul li:even"); // 偶数位 $("ul li:odd"); // 奇数位 $("ul li:gt(3)"); // 索引值大于3的li $("ul li:lt(3)"); // 索引值小于3的li $("p:not(#p2)"); // id不为p2的p标签 $("div:has(h1)") // 找到所有后代中有h1标签的div标签 $("div:has(.c1)") // 找到所有后代中有c1样式类的div标签 $("li:not(.c1)") // 找到所有不包含c1样式类的li标签 $("li:not(:has(a))") // 找到所有后代中不含a标签的li标签
2.3.4 属性选择器:
[attribute] [attribute=value] // 属性等于 [attribute!=value] // 属性不等于
【示例】:
<input type="text"> <input type="password"> <input type="checkbox"> $("input[type='checkbox']"); // 取到checkbox类型的input标签 $("input[type!='text']"); // 取到类型不是text的input标签
2.3.5 表单筛选器:
:text // 文本框 :password // 密码框 :file // 文件上传框 :radio // 单选框 :checkbox // 多选框 :submit // 提交按钮 :reset // 重置按钮 :button // 普通按钮
- 表单对象属性:
:enabled // 所有可用的标签 :disabled // 所有不可用的标签 :checked // 所有checkbox和redio已经选中的 :selected // 表单select中选中的
【示例】:找到所有的checkbox
$(":checkbox")
【示例】:找到可用的input标签
<form> <input name="email" disabled="disabled" /> <input name="id" /> </form> $("input:enabled") // 找到可用的input标签
【示例】:找到被选中的option
<select id="s1"> <option value="beijing">北京市</option> <option value="shanghai">上海市</option> <option selected value="guangzhou">广州市</option> <option value="shenzhen">深圳市</option> </select> $(":selected") // 找到所有被选中的option
2.4 筛选器方法
2.4.1 下一个元素
$("#id").next() // 找到挨着id的下一个同级标签(不含id,查找的内容是正序的) $("#id").nextAll() // 下边同级的所有(不含id,查找的内容是正序的) $("#id1").nextUntil("#id2") // 从id1到id2之间所有,往下找直到找到终止条件为止(不含id1和id2,查找的内容是正序的)
2.4.2 上一个元素
$("#id").prev() // 找到挨着id的上一个同级标签(不含id1,查找的内容是倒序的) $("#id").prevAll() // 上边同级的所有(不含id1,查找的内容是倒序的) $("#id2").prevUntil("#id1") // 从id2到id1之间所有,往上找直到找到终止条件为止(不含id1和id2,查找的内容是倒序的)
2.4.3 父亲元素
$("#id").parent() $("#id").parents() // 查找当前元素的所有的父辈元素 $("#id").parentsUntil() // 查找当前元素的所有的父辈元素,直到遇到匹配的那个元素为止。
2.4.4 儿子和兄弟元素
$("#id").children(); // 儿子们 $("#id").siblings(); // 兄弟们(前面的后面的都能找到)
2.4.5 查找
搜索所有与指定表达式匹配的元素,这个函数是找出正在处理的元素的后代元素的好方法:
$("div").find("p") // 等价于$("div p")
2.4.6 过滤
筛选出与指定表达式匹配的元素集合,这个方法用于缩小匹配的范围,用逗号分隔多个表达式:
$("div").filter(".c1") // 从结果集中过滤出有c1样式类的,等价于 $("div.c1")
【补充】:
.first() // 获取匹配的第一个元素 .last() // 获取匹配的最后一个元素 .not() // 从匹配元素的集合中删除与指定表达式匹配的元素 .has() // 保留包含特定后代的元素,去掉那些不含有指定后代的元素。 .eq() // 索引值等于指定值的元素
2.5 操作标签
2.5.1 样式操作
addClass(); // 添加指定的CSS类名。 removeClass(); // 移除指定的CSS类名。 hasClass(); // 判断样式存不存在 toggleClass(); // 切换CSS类名,如果有就移除,如果没有就添加。
【示例】:
css("color","red") //DOM操作:tag.style.color="red" $("p").css("color", "red"); //将所有p标签的字体设置为红色
Tips:修改多个样式时要传入键值对。
【示例】:左侧菜单
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>左侧菜单示例</title> <style> .left { position: fixed; left: 0; top: 0; width: 20%; height: 100%; background-color: rgb(47, 53, 61); } .right { width: 80%; height: 100%; } .menu { color: white; } .title { text-align: center; padding: 10px 15px; border-bottom: 1px solid #23282e; } .items { background-color: #181c20; } .item { padding: 5px 10px; border-bottom: 1px solid #23282e; } .hide { display: none; } </style> </head> <body> <div class="left"> <div class="menu"> <div class="title">一级菜单1</div> <div class="items"> <div class="item">二级菜单1</div> <div class="item">二级菜单2</div> <div class="item">二级菜单3</div> </div> <div class="title">一级菜单2</div> <div class="items hide"> <div class="item">二级菜单1</div> <div class="item">二级菜单2</div> <div class="item">二级菜单3</div> </div> <div class="title">一级菜单3</div> <div class="items hide"> <div class="item">二级菜单1</div> <div class="item">二级菜单2</div> <div class="item">二级菜单3</div> </div> </div> </div> <div class="right"></div> <script src="jquery-3.3.1.min.js"></script> <script> $(".title").click(function (){ // jQuery绑定事件 // 隐藏所有class里有.items的标签 $(".items").addClass("hide"); //批量操作 $(this).next().removeClass("hide"); }); </script> </body> </html>
【示例】:模态框
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>自定义模态框</title> <style> .cover { position: absolute; top: 0; right: 0; bottom: 0; left: 0; background-color: rgba(0,0,0,0.4); z-index: 998; } .modal { height: 400px; width: 600px; background-color: white; position: absolute; top: 50%; left: 50%; margin-left: -300px; margin-top: -200px; z-index: 1000; } .hide { display: none; } </style> </head> <body> <button id="b1">点我登录</button> <div class="cover hide"></div> <div class="modal hide"> <form> <p> <label>用户名: <input type="text"> </label> </p> <p> <label>密码: <input type="password"> </label> </p> <p> <input type="submit" value="登录"> <input id="cancel" type="button" value="取消"> </p> </form> </div> <script src="jquery-3.3.1.min.js"></script> <script> // 找到点击弹出模态框的按钮 $("#b1").click(function () { // 把.cover和.modal显示出来(去除掉.hide) $(".cover").removeClass("hide"); // 显示背景 $(".modal").removeClass("hide"); // 显示模态框 }); // 找到取消按钮,绑定事件 $("#cancel").click(function () { // 给背景和模态框都加上hide类 $(".cover").addClass("hide"); $(".modal").addClass("hide"); }) </script> </body> </html>
2.5.2 位置操作
offset() // 获取匹配元素在当前窗口的相对偏移或设置元素位置 position() // 获取匹配元素相对父元素的偏移 scrollTop() // 获取匹配元素相对滚动条顶部的偏移 scrollLeft() // 获取匹配元素相对滚动条左侧的偏移
Tips:.offset()方法允许我们检索一个元素相对于文档(document)的当前位置,和 .position()的差别在于 .position()是相对于相对于父级元素的位移。
【示例】:返回顶部
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="x-ua-compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>返回顶部示例</title> <style> * { margin: 0; } .c1 { width: 100px; height: 200px; background-color: red; } .c2 { height: 50px; width: 50px; position: fixed; bottom: 15px; right: 15px; background-color: #2b669a; } .hide { display: none; } .c3 { height: 100px; } </style> </head> <body> <div class="c1"></div> <div class="c3">1</div> <div class="c3">2</div> <div class="c3">3</div> <div class="c3">4</div> <div class="c3">5</div> <div class="c3">6</div> <div class="c3">7</div> <div class="c3">8</div> <div class="c3">9</div> <div class="c3">10</div> <button id="b2" class="btn btn-default c2 hide">返回顶部</button> <script src="jquery-3.3.1.min.js"></script> <script> $(window).scroll(function () { // 判断窗口距离top有多少 if ($(window).scrollTop() > 100) { // 把返回顶部的按钮显示出来, removeClass("hide"); $("#b2").removeClass("hide"); }else { $("#b2").addClass("hide"); } }); // 返回顶部的按钮 $("#b2").click(function () { $(window).scrollTop(0); }) </script> </body> </html>
2.5.3 尺寸
height() // 文本内容的高度 width() // 文本内容的宽度 innerHeight() // 文本内容的高度+ padding innerWidth() // 文本内容的宽度+ padding outerHeight() // 文本内容的高度+padding+border outerWidth() // 文本内容的宽度+padding+border
2.5.4 文本操作
2.5.4.1 HTML代码
html() // 取得第一个匹配元素的html子标签和内容,类似于innerHTML html(val) // 设置所有匹配元素的html子标签和内容
2.5.4.2 文本值
text() // 取得所有匹配元素的文本内容,类似于innerText text(val) // 设置所有匹配元素的文本内容
2.5.4.3 值
val() // 取得第一个匹配元素的当前值,默认返回的都是第一个标签的值 val(val) // 设置所有匹配元素的值 val([val1, val2]) // 设置多选的checkbox、多选select的值
2.5.4.4 示例
【示例】:设置值
<input type="checkbox" value="basketball" name="hobby">篮球 <input type="checkbox" value="football" name="hobby">足球 <select multiple id="s1"> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> </select> // 设置值 $("[name='hobby']").val(['basketball', 'football']); $("#s1").val(["1", "2"]) // select可以直接取选中的值,多选的select返回的是数组格式
【示例】:获取被选中的checkbox或radio的值
<label for="c1">女</label> <input name="gender" id="c1" type="radio" value="0"> <label for="c2">男</label> <input name="gender" id="c2" type="radio" value="1"> // 获取被选中的checkbox或radio的值 $("input[name='gender']:checked").val()
【示例】:自定义登陆校验
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>自定义登录校验示例</title> <style> .error { color: red; } </style> </head> <body> <form id="f1"> <p> <label>用户名: <input class="need" name="username" type="text"> <span class="error"></span> </label> </p> <p> <label>密码: <input class="need" name="password" type="password"> <span class="error"></span> </label> </p> <p>爱好: <label>篮球 <input name="hobby" value="basketball" type="checkbox"> </label> <label>足球 <input name="hobby" value="football" type="checkbox"> </label> <label>羽毛球 <input name="hobby" value="doublecolorball" type="checkbox"> </label> </p> <p>性别: <label>男 <input name="gender" value="1" type="radio"> </label> <label>女 <input name="gender" value="0" type="radio"> </label> <label>保密 <input name="gender" value="2" type="radio"> </label> </p> <p> <label for="s1">来源地:</label> <select name="from" id="s1"> <option value="010">北京</option> <option value="021">上海</option> <option value="020">广州</option> </select> </p> <p> <label for="s2">目的地:</label> <select name="from" id="s2" multiple> <option value="010">北京</option> <option value="021">上海</option> <option value="020">广州</option> <option value="0755">深圳</option> </select> </p> <p> <label for="t1">个人简介:</label> <textarea name="memo" id="t1" cols="30" rows="10"> </textarea> </p> <p> <input id="b1" type="submit" value="登录"> <input id="cancel" type="button" value="取消"> </p> </form> <script src="jquery-3.3.1.min.js"></script> <script> // 点击登录按钮验证用户名和密码为不为空 // 为空就在对应的input标签下面显示一个错误提示信息 // 1. 给登录按钮绑定点击事件 // 2. 点击事件要做的事 // 2.1 找到input标签--> 取值 --> 判断为不为空 --> .length为不为0 // 2.2 如果不为空,则什么都不做 // 2.2 如果为空,要做几件事 // 2.2.1 在当前这个input标签的下面 添加一个新的标签,内容为xx不能为空 $("#b1").click(function () { var $needEles = $(".need"); // 定义一个标志位 var flag = true; for (var i=0;i<$needEles.length;i++){ // 如果有错误 if ($($needEles[i]).val().trim().length === 0) { var labelName = $($needEles[i]).parent().text().trim().slice(0,-1); $($needEles[i]).next().text( labelName +"不能为空!"); // 将标志位置为false flag = false; break; } } return flag; }) </script> </body>
2.5.5 属性操作
2.5.5.1 用于ID等或自定义属性
attr(attrName) // 返回第一个匹配元素的属性值 attr(attrName, attrValue) // 为所有匹配元素设置一个属性值 attr({k1: v1, k2:v2}) // 为所有匹配元素设置多个属性值 removeAttr() // 从每一个匹配的元素中删除一个属性
2.5.5.2 用于checkbox和radio
prop() // 获取属性,返回true或false的属性 removeProp() // 移除属性
【示例】:
<input type="checkbox" value="1"> <input type="radio" value="2"> <script> $(":checkbox[value='1']").prop("checked", true); $(":radio[value='2']").prop("checked", true); </script>
2.5.5.3 prop和attr的区别
attr全称attribute(属性) ,prop全称property(属性),虽然都是属性,但他们所指的属性并不相同,attr所指的属性是HTML标签属性,而prop所指的是DOM对象属性,可以认为attr是显式的,而prop是隐式的。
- 例如:
<input type="checkbox" id="i1" value="1"> $("#i1").attr("checked") // undefined $("#i1").prop("checked") // false
可以看到attr获取一个标签内没有的东西会得到undefined,而prop获取的是这个DOM对象的属性,因此checked为false。
- 再如:
<input type="checkbox" checked id="i1" value="1"> $("#i1").attr("checked") // checked $("#i1").prop("checked") // true
这已经可以证明attr的局限性,它的作用范围只限于HTML标签内的属性,而prop获取的是这个DOM对象的属性,选中返回true,没选中返回false。
- 针对自定义属性,attr和prop的区别:
<input type="checkbox" checked id="i1" value="1" me="自定义属性"> $("#i1").attr("me") // "自定义属性" $("#i1").prop("me") // undefined
可以看到prop不支持获取标签的自定义属性。
- 总结:
- 对于标签上有的能看到的属性和自定义属性都用attr
- 对于返回布尔值的比如checkbox、radio和option的是否被选中都用prop。
Tips:在1.x及2.x版本的jQuery中使用attr对checkbox进行赋值操作时会出bug,在3.x版本的jQuery中则没有这个问题。为了兼容性,在处理checkbox和radio的时候尽量使用特定的prop(),不要使用attr("checked", "checked")。
2.5.5.4 示例
【示例】:下一张图片
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>属性操作</title> </head> <body> <img src="https://blog.leonshadow.cn/wp-content/uploads/2019/01/redis.png" alt=""> <input type="button" id="b1" value="下一个"> <script src="jquery-3.3.1.min.js"></script> <script> var oldURL; var newURL = "https://blog.leonshadow.cn/wp-content/uploads/2019/01/zabbix-1.png"; $("#b1").click(function () { var $imgEles = $("img"); // 修改img标签的src属性 oldURL = $imgEles.attr("src"); $imgEles.attr("src", newURL); newURL = oldURL; }); </script> </body> </html>
2.5.6 文档处理
2.5.6.1 添加到指定元素内部的后面
$(A).append(B) // 把B追加到A $(A).appendTo(B) // 把A追加到B
2.5.6.2 添加到指定元素内部的前面
$(A).prepend(B) // 把B前置到A $(A).prependTo(B) // 把A前置到B
2.5.6.3 添加到指定元素外部的后面
$(A).after(B) // 把B放到A的后面 $(A).insertAfter(B) // 把A放到B的后面
2.5.6.4 添加到指定元素外部的前面
$(A).before(B) // 把B放到A的前面 $(A).insertBefore(B) // 把A放到B的前面
2.5.6.5 移除和清空元素
remove() // 从DOM中删除所有匹配的元素。 empty() // 删除匹配的元素集合中所有的子节点及内容。
2.5.6.6 替换
replaceWith() // 将a标签全部替换为imgEle replaceAll() // $(imgEle).replaceAll("a");等价于 $("a").replaceWith(imgEle);
2.5.6.7 克隆
clone() // 参数
2.5.6.8 示例
【示例】:点击添加记录
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>点击添加记录示例</title> </head> <body> <table border="1" id="t1"> <thead> <tr> <th>#</th> <th>姓名</th> <th>爱好</th> <th>操作</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>leon</td> <td>技术</td> <td> <button class="delete">删除</button> </td> </tr> <tr> <td>2</td> <td>shadow</td> <td>读书</td> <td> <button class="delete">删除</button> </td> </tr> </tbody> </table> <button id="b1">添加一行数据</button> <script src="jquery-3.3.1.min.js"></script> <script> // 绑定事件 $("#b1").on("click",function () { // 生成要添加的tr标签及数据 var trEle = document.createElement("tr"); $(trEle).html("<td>3</td>" + "<td>new</td>" + "<td>line</td>" + "<td><button class='delete'>删除</button></td>"); // 把生成的tr插入到表格中 $("#t1").find("tbody").append(trEle); }); // 每一行的=删除按钮绑定事件 $("tbody").on("click",".delete",function () { $(this).parent().parent().remove(); }); </script> </body> </html>
【示例】:克隆
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>克隆示例</title> </head> <body> <button id="b1">点我克隆</button> <script src="jquery-3.3.1.min.js"></script> <script> $("#b1").click(function () { $(this).clone().insertAfter(this); }); </script> </body> </html>
2.6 事件
2.6.1 常用事件
click(function(){...}) hover(function(){...}) blur(function(){...}) focus(function(){...}) change(function(){...}) keyup(function(){...})
【示例】:键盘事件示例
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>键盘相关事件</title> </head> <body> <table border="1" id="t1"> <thead> <tr> <th>#</th> <th>姓名</th> <th>爱好</th> <th>操作</th> </tr> </thead> <tbody> <tr> <td><input type="checkbox"></td> <td>leon</td> <td>技术</td> <td> <select> <option value="0">下线</option> <option value="1">上线</option> <option value="2">离线</option> </select> </td> </tr> <tr> <td><input type="checkbox"></td> <td>leon</td> <td>技术</td> <td> <select> <option value="0">下线</option> <option value="1">上线</option> <option value="2">离线</option> </select> </td> </tr> <tr> <td><input type="checkbox"></td> <td>leon</td> <td>技术</td> <td> <select> <option value="0">下线</option> <option value="1">上线</option> <option value="2">离线</option> </select> </td> </tr> <tr> <td><input type="checkbox"></td> <td>leon</td> <td>技术</td> <td> <select> <option value="0">下线</option> <option value="1">上线</option> <option value="2">离线</option> </select> </td> </tr> <tr> <td><input type="checkbox"></td> <td>leon</td> <td>技术</td> <td> <select> <option value="0">下线</option> <option value="1">上线</option> <option value="2">离线</option> </select> </td> </tr> </tbody> </table> <script src="jquery-3.3.1.min.js"></script> <script> // 确保绑定事件的时候DOM树是生成好的 $(document).ready(function () { var mode = false; var $bodyEle = $("body"); // 给文档绑定 监听键盘按键被按下去的事件 $bodyEle.on("keydown", function (event) { // console.log(event.keyCode); if (event.keyCode === 17) { // 进入批量操作模式 mode = true; } }); // 按键抬起来的时候,退出批量操作模式 $bodyEle.on("keyup", function (event) { // console.log(event.keyCode); if (event.keyCode === 17) { // 进入批量操作模式 mode = false; } }); $("select").on("change", function () { // 取到当前select的值 var value = $(this).val(); var $thisCheckbox = $(this).parent().siblings().first().find(":checkbox"); // 判断checkbox有没有被选中 if ($thisCheckbox.prop("checked") && mode) { // 真正进入批量操作模式 var $checkedEles = $("input[type='checkbox']:checked"); for (var i = 0; i < $checkedEles.length; i++) { // 找到同一行的select $($checkedEles[i]).parent().siblings().last().find("select").val(value); } } }) }); </script> </body> </html>
2.6.2 事件绑定
2.6.2.1 绑定事件的方式
- 在标签里面写:onclick=foo(this);
- 原生DOM的JS绑定:DOM对象.onclick=function(){...}
- jQuery版的绑定事件:jQuery对象.click(function(){...})
2.6.2.2 推荐方式
.on( events [, selector ],function(){}) // 即jQuery对象.on("click", function(){...})
【解析】:
- events:事件
- selector::选择器(可选的)
- function::事件处理函数
2.6.2.3 事件冒泡和事件捕获
利用事件冒泡给已经存在的标签绑定事件,用来捕获后代标签的事件。
2.6.2.4 事件委托
事件委托是通过事件冒泡的原理,利用父标签去捕获子标签的事件。
【示例】:
// 适用于给未来的元素(页面生成的时候还没有的标签) 绑定事件 (事件委托) $("#t1").on("click", "选择器", function(){...}) // 表格中每一行的编辑和删除按钮都能触发相应的事件 $("table").on("click", ".delete", function () { // 删除按钮绑定的事件 })
2.6.3 移除事件
off() 方法移除用 .on()绑定的事件处理程序:
.off( events [, selector ][,function(){}])
2.6.4 阻止后续事件执行
return false; // 常见阻止表单提交等 e.preventDefault(); break; // for循环退出当前循环
像click、keydown等DOM中定义的事件,我们都可以使用.on()方法来绑定事件,但是hover这种jQuery中定义的事件就不能用.on()方法来绑定了。
想使用事件委托的方式绑定hover事件处理函数,可以参照如下代码分两步绑定事件:
$('ul').on('mouseenter', 'li', function() { //绑定鼠标进入事件 $(this).addClass('hover'); }); $('ul').on('mouseleave', 'li', function() { //绑定鼠标划出事件 $(this).removeClass('hover'); });
【示例】:阻止默认事件
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>阻止默认事件</title> </head> <body> <form action=""> <button id="b1">点我</button> </form> <script src="jquery-3.3.1.min.js"></script> <script> $("#b1").click(function (e) { alert(123); //return false; e.preventDefault(); }); </script> </body> </html>
2.6.5 阻止事件冒泡
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>阻止事件冒泡</title> </head> <body> <div> <p> <span>点我</span> </p> </div> <script src="jquery-3.3.1.min.js"></script> <script> $("span").click(function (e) { alert("span"); e.stopPropagation(); }); $("p").click(function () { alert("p"); }); $("div").click(function () { alert("div"); }) </script> </body> </html>
2.6.6 页面载入
当DOM载入就绪可以查询及操纵时绑定一个要执行的函数,这是事件模块中最重要的一个函数,因为它可以极大地提高web应用程序的响应速度。
// 标准写法: $(document).ready(function(){ // 在这里写你的JS代码... }) // 简单写法: $(function(){ // 你在这里写你的代码 })
【示例】:页面载入后执行
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>页面载入后执行</title> <script src="jquery-3.3.1.min.js"></script> <script> // 等DOM树生成之后 我再执行 $(document).ready(function () { console.log($("#d1").text()); // 执行绑定事件的操作 }); </script> </head> <body> <div id="d1">div标签</div> </body> </html>
2.6.7 与window.onload的区别
- onload()函数有覆盖现象,必须等待着图片资源加载完成之后才能调用
- jQuery的这个入口函数没有函数覆盖现象,文档加载完成之后就可以调用(建议使用此函数)
2.7 动画效果
2.7.1 基本
show([s,[e],[fn]]) hide([s,[e],[fn]]) toggle([s],[e],[fn])
2.7.2 滑动
slideDown([s],[e],[fn]) slideUp([s,[e],[fn]]) slideToggle([s],[e],[fn])
2.7.3 淡入淡出
fadeIn([s],[e],[fn]) fadeOut([s],[e],[fn]) fadeTo([[s],o,[e],[fn]]) fadeToggle([s,[e],[fn]])
2.7.4 自定义
animate(p,[s],[e],[fn])
【示例】:点赞特效
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="x-ua-compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>点赞特效示例</title> <style> div { position: relative; display: inline-block; } div>i { display: inline-block; color: red; position: absolute; right: -16px; top: -5px; opacity: 1; } </style> </head> <body> <div id="d1">点赞</div> <script src="jquery-3.3.1.min.js"></script> <script> $("#d1").on("click", function () { var newI = document.createElement("i"); newI.innerText = "+1"; $(this).append(newI); $(this).children("i").animate({ opacity: 0 }, 1000) }) </script> </body> </html>
2.8 补充
2.8.1 each
2.8.1.1 jQuery.each(collection, callback(indexInArray, valueOfElement))
一个通用的迭代函数,它可以用来无缝迭代对象和数组,数组和类似数组的对象通过一个长度属性(如一个函数的参数对象)来迭代数字索引,从0到length - 1。其他对象通过其属性名进行迭代。
【示例】:
var li =[10,15,20,25,30,40]; $.each(li,function(i, v){ if (v===20){ // 使用return阻止本次循环,相当于for中的continue return; } if (v===30){ return false; // 使用retun false阻止后续循环,相当于for中的break } console.log(i, v); //index是索引,ele是每次循环的具体元素。 })
2.8.1.2 .each(function(index, Element))
遍历一个jQuery对象,为每个匹配元素执行一个函数,.each() 方法用来迭代jQuery对象中的每一个DOM元素,每次回调函数执行时会传递当前循环次数作为参数(从0开始计数),由于回调函数是在当前DOM元素为上下文的语境中触发的,所以关键字 this 总是指向这个元素。
Tips: jQuery的方法返回一个jQuery对象遍历jQuery集合中的元素(隐式迭代),当这种情况发生时它通常不需要显式地循环的 .each()方法。
// 为每一个li标签添加foo $("li").each(function(){ $(this).addClass("c1"); // 注意each里面的this指向的是谁,当前循环中的li标签,是一个DOM对象 }); // 简单方式 $("li").addClass("c1"); // 对所有标签做统一操作
Tips:在遍历过程中可以使用 return false提前结束each循环:return false;
2.8.2 .data()
可以给任意的jQuery对象保存数据,在匹配的元素集合中的所有元素上存储任意相关数据或返回匹配的元素集合中的第一个元素的给定名称的数据存储的值。
2.8.2.1 .data(key, value):
在匹配的元素上存储任意相关数据:
$("div").data("k",100); // 给所有div标签都保存一个名为k,值为100
2.8.2.2 .data(key):
返回匹配的元素集合中的第一个元素的给定名称的数据存储的值,通过 .data(name, value)或 HTML5 data-*属性设置:
$("div").data("k"); // 返回第一个div标签中保存的"k"的值
2.8.2.3 .removeData(key):
移除存放在元素上的数据,不加key参数表示移除所有保存的数据:
$("div").removeData("k"); // 移除元素上存放k对应的数据
2.8.3 插件
2.8.3.1 jQuery.extend(object)
给jQuery添加全局扩展,jQuery的命名空间下添加新的功能,多用于插件开发者向 jQuery 中添加新函数时使用:
<script> jQuery.extend({ min:function(a, b){return a < b a : b;}, max:function(a, b){return a > b a : b;} }); jQuery.min(2,3);// => 2 jQuery.max(4,5);// => 5 </script>
2.8.3.2 jQuery.fn.extend(object)
给具体的jQuery对象添加扩展,一个对象的内容合并到jQuery的原型,以提供新的jQuery实例方法:
<script> jQuery.fn.extend({ check:function(){ return this.each(function(){this.checked =true;}); }, uncheck:function(){ return this.each(function(){this.checked =false;}); } }); // jQuery对象可以使用新添加的check()方法了。 $("input[type='checkbox']").check(); </script> 单独写在文件中的扩展: (function(jq){ jq.extend({ funcName:function(){ ... }, }); })(jQuery);
2.8.3.3 示例
【示例】:自定义的jQuery登录验证插件
- 【html文件】:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="x-ua-compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>登录校验插件示例</title> <style> .login-form { margin: 100px auto 0; max-width: 330px; } .login-form > div { margin: 15px 0; } .error { color: red; } </style> </head> <body> <div> <form action="" class="login-form" novalidate> <div> <label for="username">姓名</label> <input id="username" type="text" name="name" required autocomplete="off"> <span class="error"></span> </div> <div> <label for="passwd">密码</label> <input id="passwd" type="password" name="password" required autocomplete="off"> <span class="error"></span> </div> <div> <label for="mobile">手机</label> <input id="mobile" type="text" name="mobile" required autocomplete="off"> <span class="error"></span> </div> <div> <label for="where">来自</label> <input id="where" type="text" name="where" autocomplete="off"> <span class="error"></span> </div> <div> <input type="submit" value="登录"> </div> </form> </div> <script src="jquery-3.3.1.min.js"></script> <script src="validate.js"></script> <script> $.validate(); </script> </body> </html>
- 【JS文件】: validate.js
"use strict"; (function ($) { function check() { // 定义一个标志位,表示验证通过还是验证不通过 var flag = true; var errMsg; // 校验规则 $("form input[type!=':submit']").each(function () { var labelName = $(this).prev().text(); var inputName = $(this).attr("name"); var inputValue = $(this).val(); if ($(this).attr("required")) { // 如果是必填项 if (inputValue.length === 0) { // 值为空 errMsg = labelName + "不能为空"; $(this).next().text(errMsg); flag = false; return false; } // 如果是密码类型,我们就要判断密码的长度是否大于6位 if (inputName === "password") { // 除了上面判断为不为空还要判断密码长度是否大于6位 if (inputValue.length < 6) { errMsg = labelName + "必须大于6位"; $(this).next().text(errMsg); flag = false; return false; } } // 如果是手机类型,我们需要判断手机的格式是否正确 if (inputName === "mobile") { // 使用正则表达式校验inputValue是否为正确的手机号码 if (!/^1[345678]\d{9}$/.test(inputValue)) { // 不是有效的手机号码格式 errMsg = labelName + "格式不正确"; $(this).next().text(errMsg); flag = false; return false; } } } }); return flag; } function clearError(arg) { // 清空之前的错误提示 $(arg).next().text(""); } // 上面都是我定义的工具函数 $.extend({ validate: function () { $("form :submit").on("click", function () { return check(); }); $("form :input[type!='submit']").on("focus", function () { clearError(this); }); } }); })(jQuery);
【示例】:传参版jQuery登录验证插件
- 【html文件】:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="x-ua-compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>登录校验示例</title> <style> .login-form { margin: 100px auto 0; max-width: 330px; } .login-form > div { margin: 15px 0; } .error { color: red; } </style> </head> <body> <div> <form action="" class="login-form" novalidate> <div> <label for="username">姓名</label> <input id="username" type="text" name="name" required autocomplete="off"> <span class="error"></span> </div> <div> <label for="passwd">密码</label> <input id="passwd" type="password" name="password" required autocomplete="off"> <span class="error"></span> </div> <div> <label for="mobile">手机</label> <input id="mobile" type="text" name="mobile" required autocomplete="off"> <span class="error"></span> </div> <div> <label for="where">来自</label> <input id="where" type="text" name="where" autocomplete="off"> <span class="error"></span> </div> <div> <input type="submit" value="登录"> </div> </form> </div> <script src="jquery-3.3.1.min.js"></script> <script src="validate2.js"></script> <script> $.validate({"name":{"required": true}, "password": {"required": true, "minLength": 8}, "mobile": {"required": true}}); </script> </body>
- 【JS文件】:js
"use strict"; (function ($) { function check(arg) { // 定义一个标志位,表示验证通过还是验证不通过 var flag = true; var errMsg; // 校验规则 $("form input[type!=':submit']").each(function () { var labelName = $(this).prev().text(); var inputName = $(this).attr("name"); var inputValue = $(this).val(); if (arg[inputName].required) { // 如果是必填项 if (inputValue.length === 0) { // 值为空 errMsg = labelName + "不能为空"; $(this).next().text(errMsg); flag = false; return false; } // 如果是密码类型,我们就要判断密码的长度是否大于6位 if (inputName === "password") { // 除了上面判断为不为空还要判断密码长度是否大于6位 if (inputValue.length < arg[inputName].minLength) { errMsg = labelName + "必须大于"+arg[inputName].minLength+"位"; $(this).next().text(errMsg); flag = false; return false; } } // 如果是手机类型,我们需要判断手机的格式是否正确 if (inputName === "mobile") { // 使用正则表达式校验inputValue是否为正确的手机号码 if (!/^1[345678]\d{9}$/.test(inputValue)) { // 不是有效的手机号码格式 errMsg = labelName + "格式不正确"; $(this).next().text(errMsg); flag = false; return false; } } } }); return flag; } function clearError(arg) { // 清空之前的错误提示 $(arg).next().text(""); } // 上面都是我定义的工具函数 $.extend({ validate: function (arg) { $("form :submit").on("click", function () { return check(arg); }); $("form :input[type!='submit']").on("focus", function () { clearError(this); }); } }); })(jQuery);
第3章 参考资料
https://www.cnblogs.com/liwenzhou/p/8178806.html#autoid-1-9-0
