jQueryjavascript
下載連接:jQuery官網css
中文文檔:jQuery AP中文文檔html
CDN地址:<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>前端
維護IE678是一件讓人頭疼的事情,通常咱們都會額外加載一個CSS和JS單獨處理。值得慶幸的是使用這些瀏覽器的人也逐步減小,PC端用戶已經逐步被移動端用戶所取代,若是沒有特殊要求的話,通常都會選擇放棄對678的支持。java
jQuery對象就是經過jQuery包裝DOM對象後產生的對象。jQuery對象是 jQuery獨有的。若是一個對象是jQuery對象,那麼它就可使用jQuery裏的方法:例如$(「#i1」).html()。python
$("#i1").html()
的意思是:獲取id值爲 i1
的元素的html代碼。其中 html()
是jQuery裏的方法。jquery
至關於: document.getElementById("i1").innerHTML;
web
雖然 jQuery對象
是包裝 DOM對象
後產生的,可是 jQuery對象
沒法使用 DOM對象
的任何方法,同理 DOM對象
也沒不能使用 jQuery
裏的方法。正則表達式
$("#test").html() 意思是指:獲取ID爲test的元素內的html代碼。其中html()是jQuery裏的方法 這段代碼等同於用DOM實現代碼: document.getElementById(" test ").innerHTML; 雖然jQuery對象是包裝DOM對象後產生的,可是jQuery沒法使用DOM對象的任何方法,同理DOM對象也不能使用jQuery裏的方法.亂使用會報錯 約定:若是獲取的是 jQuery 對象, 那麼要在變量前面加上$. var $variable = jQuery 對象 var variable = DOM 對象 $variable[0]:jquery對象轉爲dom對象 $("#msg").html(); $("#msg")[0].innerHTML
一個約定,咱們在聲明一個jQuery對象變量的時候在變量名前面加上$:編程
var $variable = jQuery對像 var variable = DOM對象 $variable[0]//jQuery對象轉成DOM對象
拿上面那個例子舉例,jQuery對象和DOM對象的使用:
$("#i1").html();//jQuery對象可使用jQuery的方法 $("#i1")[0].innerHTML;// DOM對象使用DOM的方法
$(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
<div id="outer"> <input type="button" id="button1"> <input type="button" id="button2"> <input type="button" id="button3"> <div id="inner"> <input type="button" id="button4"> <input type="button" id="button5"> </div> </div> <input type="button" id="button6"> <input type="button" id="button7">
一、$("ancestor descendant"),選中祖先ancestor下的全部知足條件的後代descendant。
如$("#outer input")會選中button1,button2,button3,button4,button5。
二、$("parent > child"),只會選中直接子元素。
如$("#outer > input")會選中button1,button2,button3,不會選中button4,button5。
三、$("prev + next"),prev和next是兩個同級別的元素,選中緊跟在prev後面的next。
如$("#outer + input")只會選中button6,$("#button1 + input")只會選中button2。
四、$("prev ~ siblings"),prev和siblings是同級別元素,選中prev以後的全部同級別的siblings。
如$("#outer ~ input")選中button6和button7,$("#button1 ~input")選中button2和button3。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>jquery層級</title> </head> <body> <div id="outer"> <input type="button" id="button1"> <ol type="1" start="2"> <li>第一項</li> <li>第二項</li> </ol> <input type="button" id="button2"> <input type="button" id="button3"> <div id="inner"> <input type="button" id="button4"> <input type="button" id="button5"> </div> </div> <table border="1px" cellpadding="1px" cellspacing="1px" width="300px"> <thead> <tr> <th>序號</th> <th>姓名</th> <th>愛好</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>Egon</td> <td rowspan="2">槓娘</td> </tr> <tr> <td>2</td> <td>Yuan</td> </tr> </tbody> </table> <input type="button" id="button6"> <input type="button" id="button7"> <script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script> </body> </html>
基本篩選器:
:first // 第一個 :last // 最後一個 :eq(index)// 索引等於index的那個元素 :even // 匹配全部索引值爲偶數的元素,從 0 開始計數 :odd // 匹配全部索引值爲奇數的元素,從 0 開始計數 :gt(index)// 匹配全部大於給定索引值的元素 :lt(index)// 匹配全部小於給定索引值的元素 :not(元素選擇器)// 移除全部知足not條件的標籤 :has(元素選擇器)// 選取全部包含一個或多個標籤在其內的標籤(指的是從後代元素找)
$("#outer > input:first") $("#outer > input:last") $("#outer > input:eq(0)") $("#outer > input:lt(2)") $("#outer > input:even") $("#outer > input:odd")
例子:
$("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>
屬性選擇器:
[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
例子:
<form> <input name="email" disabled="disabled" /> <input name="id" /> </form> $("input:enabled") // 找到可用的input標籤
<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();// 兄弟們
查找元素:
$("#id").find()// 搜索全部與指定表達式匹配的元素。這個函數是找出正在處理的元素的後代元素的好方法。
補充:
.first()// 獲取匹配的第一個元素
.last()// 獲取匹配的最後一個元素
.not()// 從匹配元素的集合中刪除與指定表達式匹配的元素
.has()// 保留包含特定後代的元素,去掉那些不含有指定後代的元素。
$("#button7").prevUntil("#outer") r.fn.init(2) [input#button6, table, prevObject: r.fn.init(1)] $("#button7").prevUntil("#outer").not("#button6") r.fn.init [table, prevObject: r.fn.init(2)] $("#button7").prevAll() r.fn.init(3) [input#button6, table, div#outer, prevObject: r.fn.init(1)] $("#button7").prevAll().has("#button2") r.fn.init [div#outer, prevObject: r.fn.init(3)]
示例:左側菜單
<!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()
$("").offset([coordinates])
$("").position()
$("").scrollTop([val])
$("").scrollLeft([val])
示例1:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> .test1{ width: 200px; height: 200px; background-color: wheat; } </style> </head> <body> <h1>this is offset</h1> <div class="test1"></div> <p></p> <button>change</button> </body> <script src="jquery-3.1.1.js"></script> <script> var $offset=$(".test1").offset(); var lefts=$offset.left; var tops=$offset.top; $("p").text("Top:"+tops+" Left:"+lefts); $("button").click(function(){ $(".test1").offset({left:200,top:400}) }) </script> </html>
示例2:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> *{ margin: 0; } .box1{ width: 200px; height: 200px; background-color: rebeccapurple; } .box2{ width: 200px; height: 200px; background-color: darkcyan; } .parent_box{ position: relative; } </style> </head> <body> <div class="box1"></div> <div class="parent_box"> <div class="box2"></div> </div> <p></p> <script src="jquery-3.1.1.js"></script> <script> var $position=$(".box2").position(); var $left=$position.left; var $top=$position.top; $("p").text("TOP:"+$top+"LEFT"+$left) </script> </body> </html>
示例3:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> body{ margin: 0; } .returnTop{ height: 60px; width: 100px; background-color: peru; position: fixed; right: 0; bottom: 0; color: white; line-height: 60px; text-align: center; } .div1{ background-color: wheat; font-size: 5px; overflow: auto; width: 500px; height: 200px; } .div2{ background-color: darkgrey; height: 2400px; } .hide{ display: none; } </style> </head> <body> <div class="div1 div"> <h1>hello</h1> <h1>hello</h1> <h1>hello</h1> <h1>hello</h1> <h1>hello</h1> <h1>hello</h1> <h1>hello</h1> <h1>hello</h1> <h1>hello</h1> <h1>hello</h1> <h1>hello</h1> <h1>hello</h1> <h1>hello</h1> <h1>hello</h1> <h1>hello</h1> <h1>hello</h1> </div> <div class="div2 div"></div> <div class="returnTop hide">返回頂部</div> <script src="jquery-3.1.1.js"></script> <script> $(window).scroll(function(){ var current=$(window).scrollTop(); console.log(current); if (current>100){ $(".returnTop").removeClass("hide") } else { $(".returnTop").addClass("hide") } }); $(".returnTop").click(function(){ $(window).scrollTop(0) }); </script> </body> </html>
$("").height([val|fn])
$("").width([val|fn])
$("").innerHeight()
$("").innerWidth()
$("").outerHeight([soptions])
$("").outerWidth([options])
示例:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> *{ margin: 0; } .box1{ width: 200px; height: 200px; background-color: wheat; padding: 50px; border: 50px solid rebeccapurple; margin: 50px; } </style> </head> <body> <div class="box1"> DIVDIDVIDIV </div> <p></p> <script src="jquery-3.1.1.js"></script> <script> var $height=$(".box1").height(); var $innerHeight=$(".box1").innerHeight(); var $outerHeight=$(".box1").outerHeight(); var $margin=$(".box1").outerHeight(true); $("p").text($height+"---"+$innerHeight+"-----"+$outerHeight+"-------"+$margin) </script> </body> </html>
HTML代碼:
html()// 取得第一個匹配元素的html內容 html(val)// 設置全部匹配元素的html內容
文本值:
text()// 取得全部匹配元素的內容 text(val)// 設置全部匹配元素的內容
值:
val()// 取得第一個匹配元素的當前值 val(val)// 設置全部匹配元素的值 val([val1, val2])// 設置checkbox、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">
可使用:
$("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>jQuery val示例</title> </head> <body> <label for="s1">城市</label> <select id="s1"> <option value="beijing">北京市</option> <option value="shanghai">上海市</option> <option selected value="guangzhou">廣州市</option> <option value="shenzhen">深圳市</option> </select> <hr> <label for="s2">愛好</label> <select id="s2" multiple="multiple"> <option value="basketball" selected>籃球</option> <option value="football">足球</option> <option value="doublecolorball" selected>雙色球</option> </select> <script src="jquery-3.2.1.min.js"></script> <script> // 單選下拉框 $("#s1").val("shanghai"); // 多選下拉框 $("#s2").val(["basketball", "football"]); </script> </body> </html>
$("#s1").html() " <option value="beijing">北京市</option> <option value="shanghai">上海市</option> <option selected="" value="guangzhou">廣州市</option> <option value="shenzhen">深圳市</option> " $("#s1").text() " 北京市 上海市 廣州市 深圳市 " $("#s1").val() "shanghai"
<!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() // 移除屬性
--------------------------CSS類
$("").addClass(class|fn)
$("").removeClass([class|fn])
--------------------------屬性
$("").attr();
$("").removeAttr();
$("").prop();
$("").removeProp();
--------------------------HTML代碼/文本/值
$("").html([val|fn])
$("").text([val|fn])
$("").val([val|fn|arr])
---------------------------
$("#c1").css({"color":"red","fontSize":"35px"})
attr方法使用:
<input id="chk1" type="checkbox" />是否可見 <input id="chk2" type="checkbox" checked="checked" />是否可見 <script> //對於HTML元素自己就帶有的固有屬性,在處理時,使用prop方法。 //對於HTML元素咱們本身自定義的DOM屬性,在處理時,使用attr方法。 //像checkbox,radio和select這樣的元素,選中屬性對應「checked」和「selected」,這些也屬於固有屬性,所以 //須要使用prop方法去操做才能得到正確的結果。 // $("#chk1").attr("checked") // undefined // $("#chk1").prop("checked") // false // ---------手動選中的時候attr()得到到沒有意義的undefined----------- // $("#chk1").attr("checked") // undefined // $("#chk1").prop("checked") // true console.log($("#chk1").prop("checked"));//false console.log($("#chk2").prop("checked"));//true console.log($("#chk1").attr("checked"));//undefined console.log($("#chk2").attr("checked"));//checked </script>
注意:
在1.x及2.x版本的jQuery中使用attr對checkbox進行賦值操做時會出bug,在3.x版本的jQuery中則沒有這個問題。爲了兼容性,咱們在處理checkbox和radio的時候儘可能使用特定的prop(),不要使用attr("checked", "checked")。
<!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>jQuery 屬性操做</title> </head> <body> <input type="checkbox" value="1"> <input type="radio" value="2"> <script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script> <script> $(":checkbox[value='1']").prop("checked", true);<!--設置--> var status=$(":checkbox[value='1']").prop("checked");<!--獲取--> alert(status) $(":radio[value='2']").prop("checked", true); </script> </body> </html>
示例:全選、反選、取消
添加到指定元素內部的後面
$(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()
示例:
//建立一個標籤對象 $("<p>") //內部插入 $("").append(content|fn) ----->$("p").append("<b>Hello</b>"); $("").appendTo(content) ----->$("p").appendTo("div"); $("").prepend(content|fn) ----->$("p").prepend("<b>Hello</b>"); $("").prependTo(content) ----->$("p").prependTo("#foo"); //外部插入 $("").after(content|fn) ----->$("p").after("<b>Hello</b>"); $("").before(content|fn) ----->$("p").before("<b>Hello</b>"); $("").insertAfter(content) ----->$("p").insertAfter("#foo"); $("").insertBefore(content) ----->$("p").insertBefore("#foo"); //替換 $("").replaceWith(content|fn) ----->$("p").replaceWith("<b>Paragraph. </b>"); //刪除 $("").empty() $("").remove([expr]) //複製 $("").clone([Even[,deepEven]])
克隆
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(){...})
JS獲取keyCode
Event 對象:Event 對象表明事件的狀態,好比事件在其中發生的元素、鍵盤按鍵的狀態、鼠標的位置、鼠標按鈕的狀態。
事件一般與函數結合使用,函數不會在事件發生前被執行!event對象在事件發生時系統已經建立好了,而且會在事件函數被調用時傳給事件函數.咱們得到僅僅須要接收一下便可.好比onkeydown,咱們想知道哪一個鍵被按下了,須要問下event對象的屬性,這裏就是KeyCode
<input type="text" id="t1"/> <script type="text/javascript"> var ele=document.getElementById("t1"); ele.onkeydown=function(e){ e=e||window.event; var keynum=e.keyCode; var keychar=String.fromCharCode(keynum); alert(keynum+'----->'+keychar); }; </script>
keydown和keyup事件組合示例:(全選,反選,取消)
<!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> </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.2.1.min.js"></script> <script> // 全選 $("#b1").on("click", function () { $(":checkbox").prop("checked", true); }); // 取消 $("#b2").on("click", function () { $(":checkbox").prop("checked", false); }); // 反選 $("#b3").on("click", function () { $(":checkbox").each(function () { var flag = $(this).prop("checked"); $(this).prop("checked", !flag); }) }); // 按住shift鍵,批量操做 // 定義全局變量 var flag = false; // 全局事件,監聽鍵盤shift按鍵是否被按下 $(window).on("keydown", function (e) { // alert(e.keyCode); if (e.keyCode === 16){ flag = true; } }); // 全局事件,shift按鍵擡起時將全局變量置爲false $(window).on("keyup", function (e) { if (e.keyCode === 16){ flag = false; } }); // select綁定change事件 $("table select").on("change", function () { // 是否爲批量操做模式 if (flag) { var selectValue = $(this).val(); // 找到全部被選中的那一行的select,選中指定值 $("input:checked").parent().parent().find("select").val(selectValue); } }) </script> </body> </html>
實時監聽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>
//語法: 標籤對象.事件(函數)
eg: $("p").click(function(){})
hover事件:
一個模仿懸停事件(鼠標移動到一個對象上面及移出這個對象)的方法。這是一個自定義的方法,它爲頻繁使用的任務提供了一種「保持在其中」的狀態。
over:鼠標移到元素上要觸發的函數
out:鼠標移出元素要觸發的函數
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> *{ margin: 0; padding: 0; } .test{ width: 200px; height: 200px; background-color: wheat; } </style> </head> <body> <div class="test"></div> </body> <script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script> <script> function enter(){ console.log("enter") } function out(){ console.log("out") } $(".test").hover(enter,out) </script> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> *{ margin: 0; padding: 0; } .test{ width: 200px; height: 200px; background-color: wheat; } </style> </head> <body> <div class="test"></div> </body> <script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script> <script> $(".test").mouseenter(function(){ console.log("enter") }); $(".test").mouseleave(function(){ console.log("leave") }); </script> </html>
return false; // 常見阻止表單提交等
當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>
事件委託是經過事件冒泡的原理,利用父標籤去捕獲子標籤的事件。
$("").on(eve,[selector],[data],fn) // 在選擇元素上綁定一個或多個事件的事件處理函數。
示例:
表格中每一行的編輯和刪除按鈕都能觸發相應的事件。
$("table").on("click", ".delete", function () { // 刪除按鈕綁定的事件 })
<ul> <li>1</li> <li>2</li> <li>3</li> </ul> <hr> <button id="add_li">Add_li</button> <button id="off">off</button> <script src="jquery.min.js"></script> <script> $("ul li").click(function(){ alert(123) }); $("#add_li").click(function(){ var $ele=$("<li>"); $ele.text(Math.round(Math.random()*10)); $("ul").append($ele) }); // $("ul").on("click","li",function(){ // alert(456) // }) $("#off").click(function(){ $("ul li").off() }) </script>
注意:
像click、keydown等DOM中定義的事件,咱們均可以使用`.on()`方法來綁定事件,可是`hover`這種jQuery中定義的事件就不能用`.on()`方法來綁定了。
想使用事件委託的方式綁定hover事件處理函數,能夠參照以下代碼分兩步綁定事件:
$('ul').on('mouseenter', 'li', function() {//綁定鼠標進入事件 $(this).addClass('hover'); }); $('ul').on('mouseleave', 'li', function() {//綁定鼠標劃出事件 $(this).removeClass('hover'); });
HTML 4.0 的新特性之一是有能力使 HTML 事件觸發瀏覽器中的動做(action),好比當用戶點擊某個 HTML 元素時啓動一段 JavaScript。下面是一個屬性列表,這些屬性可插入 HTML 標籤來定義事件動做。
onclick 當用戶點擊某個對象時調用的事件句柄。 ondblclick 當用戶雙擊某個對象時調用的事件句柄。 onfocus 元素得到焦點。 // 練習:輸入框 onblur 元素失去焦點。 應用場景:用於表單驗證,用戶離開某個輸入框時,表明已經輸入完了,咱們能夠對它進行驗證. onchange 域的內容被改變。 應用場景:一般用於表單元素,當元素內容被改變時觸發.(select聯動) onkeydown 某個鍵盤按鍵被按下。 應用場景: 當用戶在最後一個輸入框按下回車按鍵時,表單提交. onkeypress 某個鍵盤按鍵被按下並鬆開。 onkeyup 某個鍵盤按鍵被鬆開。 onload 一張頁面或一幅圖像完成加載。 onmousedown 鼠標按鈕被按下。 onmousemove 鼠標被移動。 onmouseout 鼠標從某元素移開。 onmouseover 鼠標移到某元素之上。 onselect 在文本框中的文本被選中時發生。 onsubmit 確認按鈕被點擊,使用的對象是form。
方式一:
<div id="d1" onclick="changeColor(this);">點我</div> <script> function changeColor(ths) { ths.style.backgroundColor="green"; } </script>
注意:
this是實參,表示觸發事件的當前元素。
函數定義過程當中的ths爲形參。
方式二:
<div id="d2">點我</div> <script> var divEle2 = document.getElementById("d2"); divEle2.onclick=function () { this.innerText="呵呵"; } </script>
事件示例:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>搜索框示例</title> </head> <body> <input id="d1" type="text" value="請輸入關鍵字" onblur="blurs()" onfocus="focus()"> <script> function focus(){ var inputEle=document.getElementById("d1"); if (inputEle.value==="請輸入關鍵字"){ inputEle.value=""; } } function blurs(){ var inputEle=document.getElementById("d1"); var val=inputEle.value; if(!val.trim()){ inputEle.value="請輸入關鍵字"; } } </script> </body> </html>
<!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>select聯動</title> </head> <body> <select id="province"> <option>請選擇省:</option> </select> <select id="city"> <option>請選擇市:</option> </select> <script> data = {"河北省": ["廊坊", "邯鄲"], "北京": ["朝陽區", "海淀區"], "山東": ["威海市", "煙臺市"]}; var p = document.getElementById("province"); var c = document.getElementById("city"); for (var i in data) { var optionP = document.createElement("option"); optionP.innerHTML = i; p.appendChild(optionP); } p.onchange = function () { var pro = (this.options[this.selectedIndex]).innerHTML; var citys = data[pro]; // 清空option c.options.length = 0; for (var i=0;i<citys.length;i++) { var option_city = document.createElement("option"); option_city.innerHTML = citys[i]; c.appendChild(option_city); } } </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> <script src="jquery-2.1.4.min.js"></script> <script> $(document).ready(function() { $("#hide").click(function () { $("p").hide(1000); }); $("#show").click(function () { $("p").show(1000); }); //用於切換被選元素的 hide() 與 show() 方法。 $("#toggle").click(function () { $("p").toggle(); }); }) </script> <link type="text/css" rel="stylesheet" href="style.css"> </head> <body> <p>hello</p> <button id="hide">隱藏</button> <button id="show">顯示</button> <button id="toggle">切換</button> </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="jquery-2.1.4.min.js"></script> <script> $(document).ready(function(){ $("#slideDown").click(function(){ $("#content").slideDown(1000); }); $("#slideUp").click(function(){ $("#content").slideUp(1000); }); $("#slideToggle").click(function(){ $("#content").slideToggle(1000); }) }); </script> <style> #content{ text-align: center; background-color: lightblue; border:solid 1px red; display: none; padding: 50px; } </style> </head> <body> <div id="slideDown">出現</div> <div id="slideUp">隱藏</div> <div id="slideToggle">toggle</div> <div id="content">helloworld</div> </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="jquery-2.1.4.min.js"></script> <script> $(document).ready(function(){ $("#in").click(function(){ $("#id1").fadeIn(1000); }); $("#out").click(function(){ $("#id1").fadeOut(1000); }); $("#toggle").click(function(){ $("#id1").fadeToggle(1000); }); $("#fadeto").click(function(){ $("#id1").fadeTo(1000,0.4); }); }); </script> </head> <body> <button id="in">fadein</button> <button id="out">fadeout</button> <button id="toggle">fadetoggle</button> <button id="fadeto">fadeto</button> <div id="id1" style="display:none; width: 80px;height: 80px;background-color: blueviolet"></div> </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="jquery-2.1.4.min.js"></script> </head> <body> <button>hide</button> <p>helloworld helloworld helloworld</p> <script> $("button").click(function(){ $("p").hide(1000,function(){ alert($(this).html()) }) }) </script> </body> </html>
咱們知道,
$("p").css("color","red")
是將css操做加到全部的標籤上,內部維持一個循環;但若是對於選中標籤進行不一樣處理,這時就須要對全部標籤數組進行循環遍歷啦
jquery支持兩種循環方式:
格式:$.each(obj,fn)
li=[10,20,30,40]; dic={name:"yuan",sex:"male"}; $.each(li,function(i,x){ console.log(i,x) });
格式:$("").each(fn)
$("tr").each(function(){ console.log($(this).html()) })
其中,$(this)代指當前循環標籤。
$.each(obj,fn)
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(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>
"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);
傳參版插件:
<!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);
課後習題: