jquery的操作
jQuery
jQuery介紹
jQuery的優勢
jQuery內容:
下載鏈接:jQuery官網
中文文檔:jQuery AP中文文檔
jQuery版本
- 1.x:兼容IE678,使用最為廣泛的,官方只做BUG維護,功能不再新增。因此一般項目來說,使用1.x版本就可以了,最終版本:1.12.4 (2016年5月20日)
- 2.x:不兼容IE678,很少有人使用,官方只做BUG維護,功能不再新增。如果不考慮兼容低版本的瀏覽器可以使用2.x,最終版本:2.2.4 (2016年5月20日)
- 3.x:不兼容IE678,只支持最新的瀏覽器。需要注意的是很多老的jQuery插件不支持3.x版。目前該版本是官方主要更新維護的版本。
維護IE678是一件讓人頭疼的事情,一般我們都會額外加載一個CSS和JS單獨處理。值得慶幸的是使用這些瀏覽器的人也逐步減少,PC端用戶已經逐步被移動端用戶所取代,如果沒有特殊要求的話,一般都會選擇放棄對678的支持。
jQuery對象
jQuery對象就是通過jQuery包裝DOM對象后產生的對象。jQuery對象是 jQuery獨有的。如果一個對象是 jQuery對象,那么它就可以使用jQuery里的方法:例如$(“#i1”).html()。
$("#i1").html()的意思是:獲取id值為 i1的元素的html代碼。其中 html()是jQuery里的方法。
相當于: document.getElementById("i1").innerHTML;
雖然 jQuery對象是包裝 DOM對象后產生的,但是 jQuery對象無法使用 DOM對象的任何方法,同理 DOM對象也沒不能使用 jQuery里的方法。
一個約定,我們在聲明一個jQuery對象變量的時候在變量名前面加上$:
var $variable = jQuery對像 var variable = DOM對象 $variable[0]//jQuery對象轉成DOM對象拿上面那個例子舉例,jQuery對象和DOM對象的使用:
$("#i1").html();//jQuery對象可以使用jQuery的方法 $("#i1")[0].innerHTML;// DOM對象使用DOM的方法jQuery基礎語法
$(selector).action()
查找標簽
基本選擇器
id選擇器:
$("#id")標簽選擇器:
$("tagName")class選擇器:
$(".className")配合使用:
$("div.c1") // 找到有c1 class類的div標簽所有元素選擇器:
$("*")組合選擇器:
$("#id, .className, tagName")層級選擇器:
x和y可以為任意選擇器
$("x y");// x的所有后代y(子子孫孫) $("x > y");// x的所有兒子y(兒子) $("x + y")// 找到所有緊挨在x后面的y $("x ~ y")// x之后所有的兄弟y基本篩選器:
: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標簽 $("li:not(.c1)")// 找到所有不包含c1樣式類的li標簽 $("li:not(:has(a))")// 找到所有后代中不含a標簽的li標簽練習:
自定義模態框,使用jQuery實現彈出和隱藏功能。
<!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>.cover {position: fixed;left: 0;right: 0;top: 0;bottom: 0;background-color: darkgrey;z-index: 999;}.modal {width: 600px;height: 400px;background-color: white;position: fixed;left: 50%;top: 50%;margin-left: -300px;margin-top: -200px;z-index: 1000;}.hide {display: none;}</style> </head> <body> <input type="button" value="彈" id="i0"><div class="cover hide"></div> <div class="modal hide"><label for="i1">姓名</label><input id="i1" type="text"><label for="i2">愛好</label><input id="i2" type="text"><input type="button" id="i3" value="關閉"> </div> <script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script> <script>var tButton = $("#i0")[0];tButton.onclick=function () {var coverEle = $(".cover")[0];var modalEle = $(".modal")[0];$(coverEle).removeClass("hide");$(modalEle).removeClass("hide");};var cButton = $("#i3")[0];cButton.onclick=function () {var coverEle = $(".cover")[0];var modalEle = $(".modal")[0];$(coverEle).addClass("hide");$(modalEle).addClass("hide");} </script> </body> </html> jQuery版自定義模態框屬性選擇器:
[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"><meta http-equiv="x-ua-compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1"><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">菜單一</div><div class="items"><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> <div class="right"></div> <script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script><script>$(".title").click(function (){ // jQuery綁定事件// 隱藏所有class里有.items的標簽 $(".items").addClass("hide"); //批量操作 $(this).next().removeClass("hide");}); </script> 左側菜單示例操作標簽
樣式操作
樣式類
addClass();// 添加指定的CSS類名。 removeClass();// 移除指定的CSS類名。 hasClass();// 判斷樣式存不存在 toggleClass();// 切換CSS類名,如果有就移除,如果沒有就添加。示例:開關燈和模態框
CSS
css("color","red")//DOM操作:tag.style.color="red"示例:
$("p").css("color", "red"); //將所有p標簽的字體設置為紅色位置操作
offset()// 獲取匹配元素在當前窗口的相對偏移或設置元素位置 position()// 獲取匹配元素相對父元素的偏移 scrollTop()// 獲取匹配元素相對滾動條頂部的偏移 scrollLeft()// 獲取匹配元素相對滾動條左側的偏移.offset()方法允許我們檢索一個元素相對于文檔(document)的當前位置。
和 .position()的差別在于: .position()是相對于相對于父級元素的位移。
示例:
<!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()文本操作
HTML代碼:
html()// 取得第一個匹配元素的html內容 html(val)// 設置所有匹配元素的html內容文本值:
text()// 取得所有匹配元素的內容 text(val)// 設置所有匹配元素的內容值:
val()// 取得第一個匹配元素的當前值 val(val)// 設置所有匹配元素的值 val([val1, val2])// 設置多選的checkbox、多選select的值例如:
<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"])示例:
獲取被選中的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">可以使用:
$("input[name='gender']:checked").val() <!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(attrName)// 返回第一個匹配元素的屬性值 attr(attrName, attrValue)// 為所有匹配元素設置一個屬性值 attr({k1: v1, k2:v2})// 為所有匹配元素設置多個屬性值 removeAttr()// 從每一個匹配的元素中刪除一個屬性用于checkbox和radio
prop() // 獲取屬性 removeProp() // 移除屬性注意:
在1.x及2.x版本的jQuery中使用attr對checkbox進行賦值操作時會出bug,在3.x版本的jQuery中則沒有這個問題。為了兼容性,我們在處理checkbox和radio的時候盡量使用特定的prop(),不要使用attr("checked", "checked")。
<input type="checkbox" value="1"> <input type="radio" value="2"> <script>$(":checkbox[value='1']").prop("checked", true);$(":radio[value='2']").prop("checked", true); </script>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不支持獲取標簽的自定義屬性。
總結一下:
?
練習題:全選、反選、取消
文檔處理
添加到指定元素內部的后面
$(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 找到那些被選中行的selectvar $select = $("input:checked").parent().parent().find("select")// 2.2 給選中的select賦值 $select.val(value);}}); </script> </body> </html> 按住shift實現批量操作hover事件示例:
<!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>hover示例</title><style>* {margin: 0;padding: 0;}.nav {height: 40px;width: 100%;background-color: #3d3d3d;position: fixed;top: 0;}.nav ul {list-style-type: none;line-height: 40px;}.nav li {float: left;padding: 0 10px;color: #999999;position: relative;}.nav li:hover {background-color: #0f0f0f;color: white;}.clearfix:after {content: "";display: block;clear: both;}.son {position: absolute;top: 40px;right: 0;height: 50px;width: 100px;background-color: #00a9ff;display: none;}.hover .son {display: block;}</style> </head> <body> <div class="nav"><ul class="clearfix"><li>登錄</li><li>注冊</li><li>購物車<p class="son hide">空空如也...</p></li></ul> </div> <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script> <script> $(".nav li").hover(function () {$(this).addClass("hover");},function () {$(this).removeClass("hover");} ); </script> </body> </html> hover事件實時監聽input輸入值變化示例:
<!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>實時監聽input輸入值變化</title> </head> <body> <input type="text" id="i1"><script src="jquery-3.2.1.min.js"></script> <script>/** oninput是HTML5的標準事件* 能夠檢測textarea,input:text,input:password和input:search這幾個元素的內容變化,* 在內容修改后立即被觸發,不像onchange事件需要失去焦點才觸發* oninput事件在IE9以下版本不支持,需要使用IE特有的onpropertychange事件替代* 使用jQuery庫的話直接使用on同時綁定這兩個事件即可。* */$("#i1").on("input propertychange", function () {alert($(this).val());}) </script> </body> </html> input值變化事件事件綁定
- events: 事件
- selector: 選擇器(可選的)
- function: 事件處理函數
移除事件
off() 方法移除用?.on()綁定的事件處理程序。
- events: 事件
- selector: 選擇器(可選的)
- function: 事件處理函數
阻止后續事件執行
?
注意:
像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> <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>頁面載入
當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> 登錄校驗示例事件委托
事件委托是通過事件冒泡的原理,利用父標簽去捕獲子標簽的事件。
示例:
表格中每一行的編輯和刪除按鈕都能觸發相應的事件。
$("table").on("click", ".delete", function () {// 刪除按鈕綁定的事件 })動畫效果
// 基本 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> 點贊特效簡單示例補充
each
jQuery.each(collection, callback(indexInArray, valueOfElement)):
描述:一個通用的迭代函數,它可以用來無縫迭代對象和數組。數組和類似數組的對象通過一個長度屬性(如一個函數的參數對象)來迭代數字索引,從0到length - 1。其他對象通過其屬性名進行迭代。
li =[10,20,30,40] $.each(li,function(i, v){console.log(i, v);//index是索引,ele是每次循環的具體元素。 })輸出:
010 120 230 340.each(function(index, Element)):
描述:遍歷一個jQuery對象,為每個匹配元素執行一個函數。
.each() 方法用來迭代jQuery對象中的每一個DOM元素。每次回調函數執行時,會傳遞當前循環次數作為參數(從0開始計數)。由于回調函數是在當前DOM元素為上下文的語境中觸發的,所以關鍵字 this 總是指向這個元素。
// 為每一個li標簽添加foo $("li").each(function(){$(this).addClass("c1"); });注意: jQuery的方法返回一個jQuery對象,遍歷jQuery集合中的元素 - 被稱為隱式迭代的過程。當這種情況發生時,它通常不需要顯式地循環的 .each()方法:
也就是說,上面的例子沒有必要使用each()方法,直接像下面這樣寫就可以了:
$("li").addClass("c1"); // 對所有標簽做統一操作注意:
在遍歷過程中可以使用 return?false提前結束each循環。
終止each循環
return false;伏筆...
.data()
在匹配的元素集合中的所有元素上存儲任意相關數據或返回匹配的元素集合中的第一個元素的給定名稱的數據存儲的值。
.data(key, value):
描述:在匹配的元素上存儲任意相關數據。
$("div").data("k",100);//給所有div標簽都保存一個名為k,值為100.data(key):
描述: 返回匹配的元素集合中的第一個元素的給定名稱的數據存儲的值—通過 .data(name, value)或 HTML5 data-*屬性設置。
$("div").data("k");//返回第一個div標簽中保存的"k"的值.removeData(key):
描述:移除存放在元素上的數據,不加key參數表示移除所有保存的數據。
$("div").removeData("k"); //移除元素上存放k對應的數據示例:
模態框編輯的數據回填表格
插件(了解即可)
jQuery.extend(object)
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>jQuery.fn.extend(object)
一個對象的內容合并到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);例子:
自定義的jQuery登錄驗證插件
<!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="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script> <script src="validate.js"></script> <script>$.validate(); </script> </body> </html> HTML文件 "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); JS文件?傳參版插件:
<!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="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script> <script src="validate3.js"></script> <script>$.validate({"name":{"required": true}, "password": {"required": true, "minLength": 8}, "mobile": {"required": true}}); </script> </body> </html> HTML文件 "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); JS文件課后習題:
轉載于:https://www.cnblogs.com/huningfei/p/9693252.html
總結
- 上一篇: 数据库连接池技术
- 下一篇: VS code配置docker的shel