jQuery介绍
-
jQuery是一个轻量级的、快速简洁的、兼容多浏览器的JavaScript库。
-
jQuery使用户能够更方便地处理HTML Document、Events、实现动画效果、方便地进行Ajax交互,能够极大地简化JavaScript编程。它的宗旨就是:“Write less, do more.“(让你用更少的代码完成更多的事情)
jQuery的优势
-
一款轻量级的JS框架。jQuery核心js文件才几十kb,不会影响页面加载速度。
-
丰富的DOM选择器,jQuery的选择器用起来很方便,比如要找到某个DOM对象的相邻元素,JS可能要写好几行代码,而jQuery一行代码就搞定了,再比如要将一个表格的隔行变色,jQuery也是一行代码搞定。
-
链式表达式。jQuery的链式操作可以把多个操作写在一行代码里,更加简洁。
-
事件、样式、动画支持。jQuery还简化了js操作css的代码,并且代码的可读性也比js要强。
-
Ajax操作支持。jQuery简化了AJAX操作,后端只需返回一个JSON格式的字符串就能完成与前端的通信。
-
跨浏览器兼容。jQuery基本兼容了现在主流的浏览器,不用再为浏览器的兼容问题而伤透脑筋。
-
插件扩展开发。jQuery有着丰富的第三方的插件,例如:树形菜单、日期控件、图片切换插件、弹出窗口等等基本前端页面上的组件都有对应插件,并且用jQuery插件做出来的效果很炫,并且可以根据自己需要去改写和封装插件,简单实用。
jQuery导入问题
下载链接:
前端免费的CDN网站:
1.文件下载到了本地,如何解决多个文件反复书写引入语句的代码 可以借助与pycharm自动初始化代码功能完成自动添加 2.直接引入JQuery提供的CDN服务(基于网络直接请求加载) CDN:内容分发网络 <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.4.1/jquery.min.js"></script> 导入步骤如下:
jQuery对象
通过jQuery方法得到的标签对象称之为jQuery对象对象。jQuery对象是 jQuery独有的。如果一个对象是 jQuery对象,那么它就可以使用jQuery里的方法:
例如$(“#d1”)。
$("#d1")的意思是:获取id值为 d1 的元素的html代码。是jQuery里的方法。
相当于JS对象:document.getElementById("d1");
jQuery对象是包装原生JS对象后产生的,但是jQuery对象无法使用JS对象的任何方法,同理JS对象也不能使用jQuery里的方法。
jQuery对象与原生JS对象之间的关系:它们两个之间虽然彼此不能调用彼此的方法,但是它们两个之间是有联系的
一个约定,我们在声明一个jQuery对象变量的时候在变量名前面加上$:
$("#d1") //jQuery对象 document.getElementById("d1") //原生JS对象 $("#d1")[0] // 原生JS对象 -- 重点:注意两个对象直接的转换,容易混淆
拿上面例子举例,如何把原生JS对象转成jQuery对象:
$($("#d1")[0])//用此类方法把原生JS对象包起来得到的就是jQuery对象
jQuery基础语法
支持链式操作;
在变量前加"$"符号(var $variable = jQuery 对象);
注:此规定并不是强制要求。
$(selector).action()
查找标签
基本选择器
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.4.1/jquery.min.js"></script> </head> <body> <div id="d1" class="c1">div1</div> <div>div2</div> <span>span1</span> </body> </html>
id选择器:
$("#id")
标签选择器:
$("div")
class选择器:
$(".c1")
配合使用:
$("div.c1") // 找到class类等于c1的div标签 $("div#d1") // 找到id等于d1的div标签
所有元素选择器:
$("*")
组合选择器:
$("#id, .className, tagName")
层级选择器:
x和y可以为任意选择器
$("x y");// x的所有后代y(子子孙孙) $("x > y");// x的所有儿子y(儿子) $("x + y")// 找到所有紧挨在x后面的y $("x ~ y")// x之后所有的兄弟y
基本筛选器:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.4.1/jquery.min.js"></script> </head> <body> <ul> <li>001</li> <li>002</li> <li>003</li> <li>004</li> <li>005</li> <li>006</li> <li>007</li> <li>008</li> <li>009</li> </ul> <div> <span class="c1"></span> <span></span> <span></span> </div> <div> <p></p> </div> </body> </html>
:first // 第一个
:last // 最后一个
:eq(index) // 索引等于index的那个元素
:even // 匹配所有索引值为偶数的元素,从 0 开始计数
:odd // 匹配所有索引值为奇数的元素,从 0 开始计数
:gt(index) // 匹配所有大于给定索引值的元素
:lt(index) // 匹配所有小于给定索引值的元素
:not(元素选择器) // 移除所有满足not条件的标签
:has(元素选择器) // 选取所有包含一个或多个标签在其内的标签(指的是从后代元素找)
//例子:
$("div:has(h1)") // 找到所有后代中有h1标签的div标签
$("div:has(.c1)") // 找到所有后代中有c1样式类的div标签
$("div span:not(.c1)") // 找到div后代中所有不包含c1属性的span标签
$("li:not(:has(a))") // 找到所有后代中不含a标签的li标签
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style> * { margin: 0; padding: 0; } html,body { height: 100%; } #bg { position: absolute; top: 0; left: 0; right: 0; bottom: 0; background-color: rgba(0,0,0,0.3); display: none; } #content { position: absolute; top: 100px; left: 50%; margin-left: -150px; background-color: white; width: 300px; height: 200px; } #content p:nth-child(3) { position: absolute; top: 100px; } </style> </head> <body> <input type="button" value="弹出" id="btn"> <div id="bg"> <div id="content"> <p> <label for="inp-username">用户名: </label><input type="text" name="username" id="inp-username"> </p> <p> <label for="inp-password">密码: </label><input type="text" name="username" id="inp-password"> </p> <p> <input type="button" value="提交" > <input type="button" value="取消" id="cancel"> </p> </div> </div> <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script> <script> $("#btn")[0].onclick=function () { $("#bg").css("display","block") } $("#cancel")[0].onclick=function () { $("#inp-username").val("") $("#inp-password").val("") $("#bg").css("display","none") } </script> </body> </html>
[attribute] [attribute=value]// 属性等于 [attribute!=value]// 属性不等于 // 示例: <input type="text"> <input type="password"> <input type="checkbox"> $("input[type='checkbox']");// 取到checkbox类型的input标签 $("input[type!='text']");// 取到类型不是text的input标签
:text :password:file :radio :checkbox :submit :reset :button //示例: $(":checkbox") // 找到所有的checkbox
表单对象属性:
:enabled
:disabled
:checked
:selected
例子:
找到可用的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
下一个元素:
$("#id").next()
$("#id").nextAll()
$("#id").nextUntil("#i2")
上一个元素:
$("#id").prev()
$("#id").prevAll()
$("#id").prevUntil("#i2")
父亲元素:
$("#id").parent() $("#id").parents() // 查找当前元素的所有的父辈元素 $("#id").parentsUntil() // 查找当前元素的所有的父辈元素,直到遇到匹配的那个元素为止。
儿子和兄弟元素:
$("#id").children();// 儿子们 $("#id").siblings();// 兄弟们
查找
搜索所有与指定表达式匹配的元素。这个函数是找出正在处理的元素的后代元素的好方法。
$("div").find("p") // 等价于$("div p")
筛选
筛选出与指定表达式匹配的元素集合。这个方法用于缩小匹配的范围。用逗号分隔多个表达式。
$("div").filter(".c1") // 从结果集中过滤出有c1样式类的 //等价于 $("div.c1")
补充:
.first() // 获取匹配的第一个元素 .last() // 获取匹配的最后一个元素 .not() // 从匹配元素的集合中删除与指定表达式匹配的元素 .has() // 保留包含特定后代的元素,去掉那些不含有指定后代的元素。 .eq() // 索引值等于指定值的元素
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style> * { margin: 0; padding: 0; } html { height: 100%; } body { height: 100%; } .left { width: 20%; height: 100%; background-color: #30353c; } .title { /* 100%;*/ text-align: center; height: 50px; line-height: 50px; color: white; border-bottom: 1px solid #000; } .item { text-align: center; height: 30px; line-height: 30px; color: white; border-bottom: 1px solid #31353b; background-color: #191c20; } .hide { display: none; } </style> </head> <body> <div class="left"> <div class="menu"> <div class="title">菜单一</div> <div class="items hide"> <div class="item">111</div> <div class="item">222</div> <div class="item">333</div> </div> <div class="title">菜单二</div> <div class="items hide"> <div class="item">111</div> <div class="item">222</div> <div class="item">333</div> </div> <div class="title">菜单三</div> <div class="items hide"> <div class="item">111</div> <div class="item">222</div> <div class="item">333</div> </div> </div> </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>
操作标签
样式操作
样式类
addClass();// 添加指定的CSS类名。 removeClass();// 移除指定的CSS类名。 hasClass();// 判断样式存不存在 toggleClass();// 切换CSS类名,如果有就移除,如果没有就添加。 //示例: $('div').addClass('c1'); //往div标签class类里面添加c1属性 $('div').removeClass('c1'); //删除div标签class类里面的c1属性 $('div').addClass('c2'); //判断div标签class类里面有无c2属性
CSS
css("color","red")//DOM操作:tag.style.color="red"
示例:
$("p").css("color", "red"); //将所有p标签的字体设置为红色 // 用一行代码实现第一个p绿色,第二个p红色 $('p').first().css('color','green').next().css('color','red'); //链式操作 // $('p')拿到所有的p标签.first()给第一个标签添加css样式.next()给紧跟其后的标签添加css样式 // jQuery的链式操作使用jQuery可以做到一行代码操作很多标签 // jQuery对象调用jQuery方法之后返回的还是当前jQuery对象,也就可以继续调用
# 用python代码解释jQuery链式操作本质 class MyClass(object): def func1(self): print('from func1') return self # 一个对象调用一个方法之后再把这个对象返回出来 def func2(self): print('from func2') return self obj = MyClass() obj.func1().func2()
位置操作
offset()// 获取匹配元素在当前窗口的相对偏移或设置元素位置 position()// 获取匹配元素相对父元素的偏移 scrollTop()// 获取匹配元素相对滚动条顶部的偏移 scrollLeft()// 获取匹配元素相对滚动条左侧的偏移 .offset()方法允许我们检索一个元素相对于文档(document)的当前位置。 和 .position()的差别在于: .position()是相对于相对于父级元素的位移。
示例:
// 不加参数获取位置参数 $(".c3").offset() // 加参数设置位置参数 $(".c3").offset({top:284,left:400}) // position只能获取值,不能设置值 // scrollTop获取当前滚动条偏移量 $('window').scrollTop(); $('window').scrollTop(0); // 设置滚动条偏移量
<!DOCTYPE html> <html lang="zh-CN"> <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> .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> <button id="b1" class="btn btn-default">点我</button> <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> <div class="c3">11</div> <div class="c3">12</div> <div class="c3">13</div> <div class="c3">14</div> <div class="c3">15</div> <div class="c3">16</div> <div class="c3">17</div> <div class="c3">18</div> <div class="c3">19</div> <div class="c3">20</div> <div class="c3">21</div> <div class="c3">22</div> <div class="c3">23</div> <div class="c3">24</div> <div class="c3">25</div> <div class="c3">26</div> <div class="c3">27</div> <div class="c3">28</div> <div class="c3">29</div> <div class="c3">30</div> <div class="c3">31</div> <div class="c3">32</div> <div class="c3">33</div> <div class="c3">34</div> <div class="c3">35</div> <div class="c3">36</div> <div class="c3">37</div> <div class="c3">38</div> <div class="c3">39</div> <div class="c3">40</div> <div class="c3">41</div> <div class="c3">42</div> <div class="c3">43</div> <div class="c3">44</div> <div class="c3">45</div> <div class="c3">46</div> <div class="c3">47</div> <div class="c3">48</div> <div class="c3">49</div> <div class="c3">50</div> <div class="c3">51</div> <div class="c3">52</div> <div class="c3">53</div> <div class="c3">54</div> <div class="c3">55</div> <div class="c3">56</div> <div class="c3">57</div> <div class="c3">58</div> <div class="c3">59</div> <div class="c3">60</div> <div class="c3">61</div> <div class="c3">62</div> <div class="c3">63</div> <div class="c3">64</div> <div class="c3">65</div> <div class="c3">66</div> <div class="c3">67</div> <div class="c3">68</div> <div class="c3">69</div> <div class="c3">70</div> <div class="c3">71</div> <div class="c3">72</div> <div class="c3">73</div> <div class="c3">74</div> <div class="c3">75</div> <div class="c3">76</div> <div class="c3">77</div> <div class="c3">78</div> <div class="c3">79</div> <div class="c3">80</div> <div class="c3">81</div> <div class="c3">82</div> <div class="c3">83</div> <div class="c3">84</div> <div class="c3">85</div> <div class="c3">86</div> <div class="c3">87</div> <div class="c3">88</div> <div class="c3">89</div> <div class="c3">90</div> <div class="c3">91</div> <div class="c3">92</div> <div class="c3">93</div> <div class="c3">94</div> <div class="c3">95</div> <div class="c3">96</div> <div class="c3">97</div> <div class="c3">98</div> <div class="c3">99</div> <div class="c3">100</div> <button id="b2" class="btn btn-default c2 hide">返回顶部</button> <script src="jquery-3.2.1.min.js"></script> <script> $("#b1").on("click", function () { $(".c1").offset({left: 200, top:200}); }); $(window).scroll(function () { if ($(window).scrollTop() > 100) { $("#b2").removeClass("hide"); }else { $("#b2").addClass("hide"); } }); $("#b2").on("click", function () { $(window).scrollTop(0); }) </script> </body> </html>
尺寸:
height() width() innerHeight() innerWidth() outerHeight() outerWidth() //示例: $('p').height() // 文本 $('p').width() $('p').innerHeight // 文本+padding $('p').innerWidth $('p').outerHeight // 文本+padding+border $('p').outerWidth
文本操作
操作标签内部文本:
html() // 取得第一个匹配元素的html内容 html(val) // 设置所有匹配元素的html内容 text() // 取得所有匹配元素的内容 text(val) // 设置所有匹配元素的内容
jQuery | |
---|---|
innerText | text() |
innerHTML |
值:
val()// 取得第一个匹配元素的当前值 val(val)// 设置所有匹配元素的值 val([val1, val2])// 设置多选的checkbox、多选select的值
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.4.1/jquery.min.js"></script> </head> <body> <form action=""> <input type="text" name="username" id="d1"> </form> </body> </html>
如何获取input框用户输入的内容和文件:
<!DOCTYPE html> <html lang="zh-CN"> <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> .error { color: red; } </style> </head> <body> <form action=""> <div> <label for="input-name">用户名</label> <input type="text" id="input-name" name="name"> <span class="error"></span> </div> <div> <label for="input-password">密码</label> <input type="password" id="input-password" name="password"> <span class="error"></span> </div> <div> <input type="button" id="btn" value="提交"> </div> </form> <script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script> <script> $("#btn").click(function () { var username = $("#input-name").val(); var password = $("#input-password").val(); if (username.length === 0) { $("#input-name").siblings(".error").text("用户名不能为空"); } if (password.length === 0) { $("#input-password").siblings(".error").text("密码不能为空"); } }) </script> </body> </html>
属性操作
用于ID等或自定义属性:
attr(Name)// 返回第一个匹配元素的属性值 attr(Name, Value)// 为所有匹配元素设置一个属性值 attr({k1: v1, k2:v2})// 为所有匹配元素设置多个属性值 removeAttr()// 从每一个匹配的元素中删除一个属性 在用变量名存储对象的时候,js中推荐使用 xxxEle 标签对象 在jQuery中推荐使用 $xxxEle jQuery对象
jQuery | |
---|---|
setAttribute() | attr(name,value) |
getAttribute() | attr(name) |
removeAttribute() |
示例:
<body><p id="d1" class="c1" username="jason"></p></body> $("#d1").attr("id") // 获取id 注意括号内必须传值,否则报错 $("#d1").attr("class") // 获取class $("#d1").attr("username") // 获取自定义属性username $("#d1").attr("xxx") // 获取没有的则返回undefined $("#d1").attr("xxx","ooo") // 添加属性 $("#d1").attr({"user":"root","pwd","123"}) // 添加多个属性,需以字典形式 $("#d1").removeAttr("xxx") // 删除
用于checkbox和radio
prop() // 获取属性 removeProp() // 移除属性
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.4.1/jquery.min.js"></script> </head> <body> <p id="d1" class="c1" username="jason"></p> <input type="checkbox" checked>111 <input type="checkbox" >222 <input type="checkbox" >333 <select name="" id=""> <option value="">111</option> <option value="" selected>222</option> <option value="">333</option> </select> </body> </html>
prop和attr的区别:
attr全称attribute(属性)
prop全称property(属性)
虽然都是属性,但他们所指的属性并不相同,attr所指的属性是HTML标签属性,而prop所指的是js对象属性,可以认为attr是显式的,而prop是隐式的。
上图可以看到attr获取一个标签无论有没有被选中的都会得到checked或者undefined,而prop获取的是这个js对象的属性,因此checked为选中返回true,没选中返回false。这已经可以证明attr的局限性,它的作用范围只限于HTML标签内的属性
但要知道的是prop不支持获取标签的自定义属性。
总结一下:
-
对于标签上有的能看到的属性和自定义属性都用attr
-
对于返回布尔值的比如checkbox、radio和option的是否被选中都用prop。
文档处理
添加到指定元素内部的后面
$(A).append(B)// 把B追加到A $(A).appendTo(B)// 把A追加到B
添加到指定元素内部的前面
$(A).prepend(B)// 把B前置到A $(A).prependTo(B)// 把A前置到B
添加到指定元素外部的后面
$(A).after(B)// 把B放到A的后面 $(A).insertAfter(B)// 把A放到B的后面
添加到指定元素外部的前面
$(A).before(B)// 把B放到A的前面 $(A).insertBefore(B)// 把A放到B的前面
移除和清空元素
remove()// 从DOM中删除所有匹配的元素。 empty()// 删除匹配的元素集合中所有的子节点。
例子:
点击按钮在表格添加一行数据。
点击每一行的删除按钮删除当前行数据。
替换
replaceWith()
replaceAll()
克隆
clone()// 参数
<!DOCTYPE html> <html lang="zh-CN"> <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> #b1 { background-color: deeppink; padding: 5px; color: white; margin: 5px; } #b2 { background-color: dodgerblue; padding: 5px; color: white; margin: 5px; } </style> </head> <body> <button id="b1">屠龙宝刀,点击就送</button> <hr> <button id="b2">屠龙宝刀,点击就送</button> <script src="jquery-3.2.1.min.js"></script> <script> // clone方法不加参数true,克隆标签但不克隆标签带的事件 $("#b1").on("click", function () { $(this).clone().insertAfter(this); }); // clone方法加参数true,克隆标签并且克隆标签带的事件 $("#b2").on("click", function () { $(this).clone(true).insertAfter(this); }); </script> </body> </html> 点击复制按钮
事件
常用事件
click(function(){...})
hover(function(){...})
blur(function(){...})
focus(function(){...})
change(function(){...})
keyup(function(){...})
keydown和keyup事件组合示例:
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta http-equiv="content-Type" charset="UTF-8"> <meta http-equiv="x-ua-compatible" content="IE=edge"> <title>Title</title> </head> <body> <table border="1"> <thead> <tr> <th>#</th> <th>姓名</th> <th>操作</th> </tr> </thead> <tbody> <tr> <td><input type="checkbox"></td> <td>Egon</td> <td> <select> <option value="1">上线</option> <option value="2">下线</option> <option value="3">停职</option> </select> </td> </tr> <tr> <td><input type="checkbox"></td> <td>Alex</td> <td> <select> <option value="1">上线</option> <option value="2">下线</option> <option value="3">停职</option> </select> </td> </tr> <tr> <td><input type="checkbox"></td> <td>Yuan</td> <td> <select> <option value="1">上线</option> <option value="2">下线</option> <option value="3">停职</option> </select> </td> </tr> <tr> <td><input type="checkbox"></td> <td>EvaJ</td> <td> <select> <option value="1">上线</option> <option value="2">下线</option> <option value="3">停职</option> </select> </td> </tr> <tr> <td><input type="checkbox"></td> <td>Gold</td> <td> <select> <option value="1">上线</option> <option value="2">下线</option> <option value="3">停职</option> </select> </td> </tr> </tbody> </table> <input type="button" id="b1" value="全选"> <input type="button" id="b2" value="取消"> <input type="button" id="b3" value="反选"> <script src="jquery-3.3.1.js"></script> <script> var flag = false; // shift按键被按下的时候 $(window).keydown(function (event) { console.log(event.keyCode); if (event.keyCode === 16){ flag = true; } }); // shift按键被抬起的时候 $(window).keyup(function (event) { console.log(event.keyCode); if (event.keyCode === 16){ flag = false; } }); // select标签的值发生变化的时候 $("select").change(function (event) { // 如果shift按键被按下,就进入批量编辑模式 // shift按键对应的code是16 // 判断当前select这一行是否被选中 console.log($(this).parent().siblings().first().find(":checkbox")); var isChecked = $(this).parent().siblings().first().find(":checkbox").prop("checked"); console.log(isChecked); if (flag && isChecked) { // 进入批量编辑模式 // 1. 取到当前select选中的值 var value = $(this).val(); // 2. 给其他被选中行的select设置成和我一样的值 // 2.1 找到那些被选中行的select var $select = $("input:checked").parent().parent().find("select") // 2.2 给选中的select赋值 $select.val(value); } }); </script> </body> </html>
hover事件示例:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <p>戒了烟我不习惯,没有你我怎么办,三年零一个礼拜,要怎么学会忍耐!</p> <script src="jQuery-3.3.1.js"> </script> <script> $('p').hover( function () { alert('哈喽,老北鼻!') }, function () { alert('你个嘚嘚儿') } ) </script> </body> </html>
实时监听input输入值变化示例:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.4.1/jquery.min.js"></script> </head> <body> <input type="text" id="d1"> <script> $('#d1').on('input',function () { console.log($(this).val()) }) </script> </body> </html>
input值变化事件
事件绑定
-
.on( events [, selector ],function(){})
-
events: 事件
-
selector: 选择器(可选的)
-
function: 事件处理函数
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script> $(function () { // 等待文档加载完毕之后再执行 }) </script> </head> <body> <button id="d1">点我点我</button> <script> $('#d1').on('click',function () { alert(666) }) // jQuery绑定事件的方式 // $('#d1').click(function () { // alert(123) // }) // 原生JS绑定事件方法1 // function sendMsg() { // prompt('你好啊') // } // 原生JS绑定事件方法2 // var btnEle = document.getElementById('d1'); // btnEle.onclick = function () { // confirm('你好啊') // } </script> </body> </html>
移除事件
-
.off( events [, selector ][,function(){}])
off()
方法移除用 .on()
绑定的事件处理程序。
-
events: 事件
-
selector: 选择器(可选的)
-
function: 事件处理函数
阻止后续事件执行
-
return false; // 常见阻止表单提交等
-
e.preventDefault();
<!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>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.4.1/jquery.min.js"></script> </head> <body> <form action=""> <span id="d2" style="color: red"></span> <input type="submit" id="d1"> </form> <script> $('#d1').click(function () { $('#d2').text('有点饿了 干饭干饭!'); return false }) </script> </body> </html>
注意:
像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</title> <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.4.1/jquery.min.js"></script> </head> <body> <div id="d1">div <p id="d2">p <span id="d3">span</span> </p> </div> <script> $('#d1').click(function (e) { alert('div') }); $('#d2').click(function (e) { alert('p') }); $('#d3').click(function (e) { alert('span') e.stopPropagation() }) </script> </body> </html>
页面载入
当DOM载入就绪可以查询及操纵时绑定一个要执行的函数。这是事件模块中最重要的一个函数,因为它可以极大地提高web应用程序的响应速度。
// 两种写法: $(document).ready(function(){ // 在这里写你的JS代码... }) //简写: $(function(){ // 你在这里写你的代码 })
文档加载完绑定事件,并且阻止默认事件发生:
<!DOCTYPE html> <html lang="zh-CN"> <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> .error { color: red; } </style> </head> <body> <form id="myForm"> <label for="name">姓名</label> <input type="text" id="name"> <span class="error"></span> <label for="passwd">密码</label> <input type="password" id="passwd"> <span class="error"></span> <input type="submit" id="modal-submit" value="登录"> </form> <script src="jquery-3.2.1.min.js"></script> <script src="s7validate.js"></script> <script> function myValidation() { // 多次用到的jQuery对象存储到一个变量,避免重复查询文档树 var $myForm = $("#myForm"); $myForm.find(":submit").on("click", function () { // 定义一个标志位,记录表单填写是否正常 var flag = true; $myForm.find(":text, :password").each(function () { var val = $(this).val(); if (val.length <= 0 ){ var labelName = $(this).prev("label").text(); $(this).next("span").text(labelName + "不能为空"); flag = false; } }); // 表单填写有误就会返回false,阻止submit按钮默认的提交表单事件 return flag; }); // input输入框获取焦点后移除之前的错误提示信息 $myForm.find("input[type!='submit']").on("focus", function () { $(this).next(".error").text(""); }) } // 文档树就绪后执行 $(document).ready(function () { myValidation(); }); </script> </body> </html>
与window.onload的区别
-
window.onload()函数有覆盖现象,必须等待着图片资源加载完成之后才能调用
-
jQuery的这个入口函数没有函数覆盖现象,文档加载完成之后就可以调用(建议使用此函数)
事件委托
事件委托是通过事件冒泡的原理,利用父标签去捕获子标签的事件。
示例:
表格中每一行的编辑和删除按钮都能触发相应的事件。
$("table").on("click", ".delete", function () { // 删除按钮绑定的事件 })
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.4.1/jquery.min.js"></script> </head> <body> <button>按钮</button> <script> // $('button').click(function () { // alert(123) // }) // 事件委托 将body内部所有的点击事件委托给button按钮 $('body').on('click','button',function () { alert(123) }) </script> </body> </html>
动画效果
// 基本 show([s,[e],[fn]]) hide([s,[e],[fn]]) toggle([s],[e],[fn]) // 滑动 slideDown([s],[e],[fn]) slideUp([s,[e],[fn]]) slideToggle([s],[e],[fn]) // 淡入淡出 fadeIn([s],[e],[fn]) fadeOut([s],[e],[fn]) fadeTo([[s],o,[e],[fn]]) fadeToggle([s,[e],[fn]]) // 自定义(了解即可) animate(p,[s],[e],[fn])
自定义动画示例:
<!DOCTYPE html> <html lang="zh-CN"> <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.2.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>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> .box{ width: 80px; height: 80px; text-align: center; line-height: 50px; margin: 20px auto; position: relative; border: 5px solid #7eff99; border-radius: 50%; background-image: url("https://gitee.com/geng-feng/blogimage/raw/master/images/12.jpg"); background-repeat: round; } .son { font-size:28px; color:salmon; display: none; position: absolute; right: -20px; top: -30px; } </style> </head> <body> <div class="box"> <div class="son">+1</div> </div> <script> var box = document.getElementsByClassName("box")[0]; box.onclick = function () { var son = document.getElementsByClassName("son")[0]; son.style.display="block"; setTimeout(function () { son.style.display="none"; },1000) } </script> </body> </html>
Bootstrap
1、下载源文件使用 2、CDN """Bootstrap是基于jQuery开发的""" # 使用Bootstrap最好提前把jQuery先导入 """ 在使用Bootstrap的时候建议你第一次使用本地文件导入的方式 之后再使用CDN 原因:让pycharm能够加载并在后期自动提示bootstrap相关代码 """ 我们使用框架操作标签样式只需要修改class属性即可
<div class="container-fluid"> </div> <div class="container"> </div>
<div class="row">12份</div> <div class="col-md-n"></div>