目錄css
下載連接:jQuery官網html
中文文檔:jQuery AP中文文檔前端
維護IE678是一件讓人頭疼的事情,通常咱們都會額外加載一個CSS和JS單獨處理。值得慶幸的是使用這些瀏覽器的人也逐步減小,PC端用戶已經逐步被移動端用戶所取代,若是沒有特殊要求的話,通常都會選擇放棄對678的支持。jquery
jQuery對象就是經過jQuery包裝DOM對象後產生的對象。jQuery對象是 jQuery獨有的。若是一個對象是 jQuery對象,那麼它就可使用jQuery裏的方法:例如$(「#i1」).html()。web
$("#i1").html()
的意思是:獲取id值爲 i1
的元素的html代碼。其中 html()
是jQuery裏的方法。正則表達式
至關於: document.getElementById("i1").innerHTML;
編程
雖然 jQuery對象
是包裝 DOM對象
後產生的,可是 jQuery對象
沒法使用 DOM對象
的任何方法,同理 DOM對象
也沒不能使用 jQuery
裏的方法。bootstrap
一個約定,咱們在聲明一個jQuery對象變量的時候在變量名前面加上$:後端
var $variable = jQuery對像 var variable = DOM對象 $variable[0]//jQuery對象轉成DOM對象
拿上面那個例子舉例,jQuery對象和DOM對象的使用:數組
$("#i1").html();//jQuery對象可使用jQuery的方法 $("#i1")[0].innerHTML;// DOM對象使用DOM的方法
$(selector).action()
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>jquery</title> <!--jquery--> <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script> <link rel="stylesheet" href="https://cdn.bootcss.com/twitter-bootstrap/3.3.1/css/bootstrap.min.css"> <script src="https://cdn.bootcss.com/twitter-bootstrap/3.3.1/js/bootstrap.min.js"></script> <style> div{height: 100px} </style> </head> <body> <div class="a" id="a1">第一個div <div class="b" id="b1" name="sky">第一個div下的div1</div> <span class="c" id="c1">第一個div下的span</span> </div> <br> <br> <br> <div class="d" id="d1">第二個div <input type="text" id="i1"> <input type="checkbox" id="i2" checked>嘿嘿 <input type="text" id="i3"> <input type="radio" id="i4" checked>男 </div> <select name="" id="s1"> <option value="" id="o1">上海</option> <option value="" id="o2">北京</option> <option value="" id="o3" selected>南京</option> </select> <div class="e" id="e1" name="ocean">第三個div</div> <div class="f" id="f1">第四個div</div> </body> </html>
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="en"> <head> <meta charset="UTF-8"> <title>自定義模態框</title> <!--jquery--> <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script> <link rel="stylesheet" href="https://cdn.bootcss.com/twitter-bootstrap/3.3.1/css/bootstrap.min.css"> <script src="https://cdn.bootcss.com/twitter-bootstrap/3.3.1/js/bootstrap.min.js"></script> <style> .cover { position: fixed; left: 0; right: 0; top: 0; bottom: 0; background-color: peachpuff; z-index: 99; } .moda { width: 600px; height: 400px; background-color: yellow; position: fixed; left: 50%; top: 50%; margin-left: -300px; margin-top: -200px; z-index: 100; } .hide { display: none; } </style> </head> <body> <input type="button" value="彈" id="i0"> <div class="cover hide"> </div> <div class="moda hide"> <label for="i1">姓名</label> <input type="text" id="i1"> <label for="i2"></label> <input type="text" id="i2"> <input type="button" id="i3" value="關閉"> </div> <script> var tButton = $("#i0")[0]; tButton.onclick = function () { var coverEle = $(".cover")[0]; var modalEge = $(".moda")[0]; $(coverEle).removeClass("hide"); $(modalEge).removeClass("hide"); }; var cButton = $("#i3")[0]; cButton.onclick = function () { var coverEle = $(".cover")[0]; var modalEge = $(".moda")[0]; $(coverEle).addClass("hide"); $(modalEge).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
找到被選中的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("span")
等價於$("div span")
篩選
篩選出與指定表達式匹配的元素集合。這個方法用於縮小匹配的範圍。用逗號分隔多個表達式。
$("div").filter(".c1") // 從結果集中過濾出有c1樣式類的
等價於 $("div.c1")
補充:
.first() // 獲取匹配的第一個元素 .last() // 獲取匹配的最後一個元素 .not() // 從匹配元素的集合中刪除與指定表達式匹配的元素 .has() // 保留包含特定後代的元素,去掉那些不含有指定後代的元素。 .eq() // 索引值等於指定值的元素
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>左側菜單示例</title> <!--jquery--> <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script> <link rel="stylesheet" href="https://cdn.bootcss.com/twitter-bootstrap/3.3.1/css/bootstrap.min.css"> <script src="https://cdn.bootcss.com/twitter-bootstrap/3.3.1/js/bootstrap.min.js"></script> <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 #ff5b28; } .items{ background-color: palevioletred; } .item{ padding: 5px 10px; border-bottom: 1px solid #ffc8bd; } .hide{ display: none; } </style> </head> <body> <div class="left"> <div class="menu"> <div class="item"> <div class="title">菜單1</div> <div class="items"> <div class="item">111</div> <div class="item">222</div> <div class="item">333</div> </div> </div> <div class="item"> <div class="title">菜單2</div> <div class="items hide"> <div class="item">111</div> <div class="item">222</div> <div class="item">333</div> </div> </div> <div class="item"> <div class="title">菜單3</div> <div class="items hide"> <div class="item">111</div> <div class="item">222</div> <div class="item">333</div> </div> </div> </div> </div> <div class="right"></div> <script> $(".title").click(function () {//jQuery綁定的事件 //隱藏全部的class裏面的.items的標籤 // $(".items").addClass("hide"); //批量操做 // $(this).next().removeClass("hide"); // jQuery鏈式操做 $(this).next().removeClass('hide').parent().siblings().find('.items').addClass('hide') }) </script> </body> </html>
樣式類
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: 10000px; width: 800px; border: 1px solid purple; background-color: purple; } </style> </head> <body> <button id="b1" class="btn btn-default">點我</button> <div class="c1"></div> <div class="c3">1</div> <button id="b2" class="btn btn-default c2 hide">返回頂部</button> <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script> <script> $("#b1").on("click", function () { $(".c1").offset({left: 200, top:200}); }); $(".c1").on("click", function () { $(".c1").offset({left: 8, top:33}); }); $(window).scroll(function () { if ($(window).scrollTop() > 50) { $("#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="text" 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>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script> <link href="https://cdn.bootcss.com/twitter-bootstrap/3.3.1/css/bootstrap.min.css" rel="stylesheet"> <script src="https://cdn.bootcss.com/twitter-bootstrap/3.3.1/js/bootstrap.min.js"></script> <style> .hid{ display: none; } </style> </head> <body> <form> <input type="text" value="" id ="id"><span class="hid">不能爲空</span> <br> <input type="submit" value="拜拜!" id="sub"> </form> <script> $("#sub").on("click",function (e) { var data= $("#id").val(); if(!data.trim()){ $(".hid").removeClass("hid"); //第一種阻止事件的方法 // return false //第二種阻止事件的方法 e.preventDefault() } }) </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內部添加B) $(A).appendTo(B)// 把A追加到B(在B的內部添加A)
添加到指定元素內部的前面
$(A).prepend(B)// 把B前置到A(在A內部添加B而且置頂) $(A).prependTo(B)// 把A前置到B(在B的內部添加A,而且置頂)
添加到指定元素外部的後面
$(A).after(B)// 把B放到A的後面 $(A).insertAfter(B)// 把A放到B的後面
添加到指定元素外部的前面
$(A).before(B)// 把B放到A的前面 $(A).insertBefore(B)// 把A放到B的前面
移除和清空元素
remove()// 從DOM中刪除全部匹配的元素。 empty()// 刪除匹配的元素集合中全部的子節點。
替換
replaceWith()#A被B替換 A.replaceAll(B)#A把B頂替
克隆
clone()// 參數
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script> <link href="https://cdn.bootcss.com/twitter-bootstrap/3.3.1/css/bootstrap.min.css" rel="stylesheet"> <script src="https://cdn.bootcss.com/twitter-bootstrap/3.3.1/js/bootstrap.min.js"></script> </head> <body> <button>來啊,來啊</button> <script> $("button").click(function () { $(this).clone(true).insertAfter(this) }) </script> </body> </html>
click(function(){...}) hover(function(){...}) blur(function(){...}) focus(function(){...}) change(function(){...}) keyup(function(){...})
方法 | 描述 |
---|---|
bind() | 向元素添加事件處理程序 |
blur() | 添加/觸發失去焦點事件 |
hover() | 添加兩個事件處理程序到 hover 事件 |
change() | 添加/觸發 change 事件 |
click() | 添加/觸發 click 事件 |
dblclick() | 添加/觸發 double click 事件 |
focus() | 添加/觸發 focus 事件 |
keyup() | 添加/觸發 keyup 事件 |
focusin() | 添加事件處理程序到 focusin 事件 |
focusout() | 添加事件處理程序到 focusout 事件 |
keydown() | 添加/觸發 keydown 事件 |
keypress() | 添加/觸發 keypress 事件 |
delegate() | 向匹配元素的當前或將來的子元素添加處理程序 |
live() | 在版本 1.9 中被移除。添加一個或多個事件處理程序到當前或將來的被選元素 |
load() | 在版本 1.8 中被廢棄。添加一個事件處理程序到 load 事件 |
mousedown() | 添加/觸發 mousedown 事件 |
mouseenter() | 添加/觸發 mouseenter 事件 |
mouseleave() | 添加/觸發 mouseleave 事件 |
mousemove() | 添加/觸發 mousemove 事件 |
mouseout() | 添加/觸發 mouseout 事件 |
mouseover() | 添加/觸發 mouseover 事件 |
mouseup() | 添加/觸發 mouseup 事件 |
off() | 移除經過 on() 方法添加的事件處理程序 |
on() | 向元素添加事件處理程序 |
one() | 向被選元素添加一個或多個事件處理程序。該處理程序只能被每一個元素觸發一次 |
$.proxy() | 接受一個已有的函數,並返回一個帶特定上下文的新的函數 | | ready() | 規定當 DOM 徹底加載時要執行的函數 | | resize() | 添加/觸發 resize 事件 | | scroll() | 添加/觸發 scroll 事件 | | select() | 添加/觸發 select 事件 | | submit() | 添加/觸發 submit 事件 | | toggle() | 在版本 1.9 中被移除。添加 click 事件之間要切換的兩個或多個函數 | | trigger() | 觸發綁定到被選元素的全部事件 | | triggerHandler() | 觸發綁定到被選元素的指定事件上的全部函數 | | unbind() | 從被選元素上移除添加的事件處理程序 | | undelegate() | 從如今或將來的被選元素上移除事件處理程序 | | unload() | 在版本 1.8 中被廢棄。添加事件處理程序到 unload 事件 | | contextmenu() | 添加事件處理程序到 contextmenu 事件 | | $.holdReady() |
用於暫停或恢復.ready() 事件的執行 |
die() | 在版本 1.9 中被移除。移除全部經過 live() 方法添加的事件處理程序 |
error() | 在版本 1.8 中被廢棄。添加/觸發 error 事件 |
event.currentTarget | 在事件冒泡階段內的當前 DOM 元素 |
event.data | 包含當前執行的處理程序被綁定時傳遞到事件方法的可選數據 |
event.delegateTarget | 返回當前調用的 jQuery 事件處理程序所添加的元素 |
event.isDefaultPrevented() | 返回指定的 event 對象上是否調用了 event.preventDefault() |
event.isImmediatePropagationStopped() | 返回指定的 event 對象上是否調用了 event.stopImmediatePropagation() |
event.isPropagationStopped() | 返回指定的 event 對象上是否調用了 event.stopPropagation() |
event.namespace | 返回當事件被觸發時指定的命名空間 |
event.pageX | 返回相對於文檔左邊緣的鼠標位置 |
event.pageY | 返回相對於文檔上邊緣的鼠標位置 |
event.preventDefault() | 阻止事件的默認行爲 |
event.relatedTarget | 返回當鼠標移動時哪一個元素進入或退出 |
event.result | 包含由被指定事件觸發的事件處理程序返回的最後一個值 |
event.stopImmediatePropagation() | 阻止其餘事件處理程序被調用 |
event.stopPropagation() | 阻止事件向上冒泡到 DOM 樹,阻止任何父處理程序被事件通知 |
event.target | 返回哪一個 DOM 元素觸發事件 |
event.timeStamp | 返回從 1970 年 1 月 1 日到事件被觸發時的毫秒數 |
event.type | 返回哪一種事件類型被觸發 |
event.which | 返回指定事件上哪一個鍵盤鍵或鼠標按鈕被按下 |
event.metaKey | 事件觸發時 META 鍵是否被按下 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <!--jquery--> <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script> <link rel="stylesheet" href="https://cdn.bootcss.com/twitter-bootstrap/3.3.1/css/bootstrap.min.css"> <script src="https://cdn.bootcss.com/twitter-bootstrap/3.3.1/js/bootstrap.min.js"></script> </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 name=""> <option value="1">上線</option> <option value="3">下線</option> <option value="4">停職</option> </select> </td> </tr> <tr> <td><input type="checkbox"></td> <td>Egon</td> <td> <select name=""> <option value="1">上線</option> <option value="3">下線</option> <option value="4">停職</option> </select> </td> </tr> <tr> <td><input type="checkbox"></td> <td>Egon</td> <td> <select name=""> <option value="1">上線</option> <option value="3">下線</option> <option value="4">停職</option> </select> </td> </tr> <tr> <td><input type="checkbox"></td> <td>Egon</td> <td> <select name=""> <option value="1">上線</option> <option value="3">下線</option> <option value="4">停職</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> var flag = false; //shift鍵按下的時候 (window).onkeydown(function (event) { console.log(event.keyCode); if (event.keyCode == 16) { flag = true; } }); //shift按鍵被擡起的時候 (window).onkeyup(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>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script> <link href="https://cdn.bootcss.com/twitter-bootstrap/3.3.1/css/bootstrap.min.css" rel="stylesheet"> <script src="https://cdn.bootcss.com/twitter-bootstrap/3.3.1/js/bootstrap.min.js"></script> </head> <body> <div style="width: 200px;height: 200px;background-color: red">來玩啊</div> <script> $("div").hover( function () { alert("很開心爲你服務"); }, function () { alert("大爺,慢走,下次再來") } ) </script> </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <!--jquery--> <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script> <link rel="stylesheet" href="https://cdn.bootcss.com/twitter-bootstrap/3.3.1/css/bootstrap.min.css"> <script src="https://cdn.bootcss.com/twitter-bootstrap/3.3.1/js/bootstrap.min.js"></script> </head> <body> <p>當你在以上輸入框中輸入內容時,div 中會陷入輸入鍵的數字碼。</p> 請輸入:<input type="text"> <div></div> <span></span> <script> $("input").on("input",function () { console.log($(this).val()) }); $("input").keydown(function (event) { $("div").html("按鍵key:"+event.which); $("span").html("按鍵key:"+event.keyCode) }); </script> </body> </html>
.on( events [, selector ],function(){})
.off( events [, selector ][,function(){}])
off()
方法移除用 .on()
綁定的事件處理程序。
return false; // 常見阻止表單提交等
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>阻止後續事件</title> <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script> <link href="https://cdn.bootcss.com/twitter-bootstrap/3.3.1/css/bootstrap.min.css" rel="stylesheet"> <script src="https://cdn.bootcss.com/twitter-bootstrap/3.3.1/js/bootstrap.min.js"></script> <style> .hid{ display: none; } </style> </head> <body> <form> <input type="text" value="" id ="id"><span class="hid">不能爲空</span> <br> <input type="submit" value="拜拜!" id="sub"> </form> <script> $("#sub").on("click",function (e) { var data= $("#id").val(); if(!data.trim()){ $(".hid").removeClass("hid"); //第一種阻止事件的方法 // return false //第二種阻止事件的方法 e.preventDefault() } }) </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.bootcss.com/jquery/3.4.1/jquery.min.js"></script> <link href="https://cdn.bootcss.com/twitter-bootstrap/3.3.1/css/bootstrap.min.css" rel="stylesheet"> <script src="https://cdn.bootcss.com/twitter-bootstrap/3.3.1/js/bootstrap.min.js"></script> <style> #a{ width: 500px; height: 500px; background-color: red; } #b{ width: 400px; height: 400px; background-color: green; } #c{ width: 200px; height: 200px; background-color: black; } </style> <script> // $(document).ready(function(){ // // $("#a").on("click",function () { // alert("第一") // }); // $("#b").on("click",function (e) { // alert("第er") // e.stopPropagation() // }); // $("#c").on("click",function (e) { // alert("第san"); // // }); // // }) $(function(){ $("#a").on("click",function () { alert("第一") }); $("#b").on("click",function (e) { alert("第er") e.stopPropagation() }); $("#c").on("click",function (e) { alert("第san"); }); }) </script> </head> <body> <div id="a"> <div id="b"> <div id="c"></div> </div> </div> </body> </html>
當DOM載入就緒能夠查詢及操縱時綁定一個要執行的函數。這是事件模塊中最重要的一個函數,由於它能夠極大地提升web應用程序的響應速度。
兩種寫法:
$(document).ready(function(){ // 在這裏寫你的JS代碼... })
簡寫:
$(function(){ // 你在這裏寫你的代碼 })
事件委託是經過事件冒泡的原理,利用父標籤去捕獲子標籤的事件。
示例:
表格中每一行的編輯和刪除按鈕都能觸發相應的事件。
$("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="en"> <head> <meta charset="UTF-8"> <title>Title</title> <!--jquery--> <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script> <link rel="stylesheet" href="https://cdn.bootcss.com/twitter-bootstrap/3.3.1/css/bootstrap.min.css"> <script src="https://cdn.bootcss.com/twitter-bootstrap/3.3.1/js/bootstrap.min.js"></script> <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> $("#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>
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"> <title>Title</title> <!--jquery--> <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script> <link rel="stylesheet" href="https://cdn.bootcss.com/twitter-bootstrap/3.3.1/css/bootstrap.min.css"> <script src="https://cdn.bootcss.com/twitter-bootstrap/3.3.1/js/bootstrap.min.js"></script> <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 type="text" id="username" name="name" required autocomplete="off"> <span class="error"></span> </div> <div> <label for="password">密碼</label> <input type="text" id="password" name="password" required autocomplete="off"> <span class="error"></span> </div> <div> <label for="mobile">手機</label> <input type="text" id="mobile" name="mobile" required autocomplete="off"> <span class="error"></span> </div> <div> <label for="where">來自</label> <input type="text" id="where" name="where" autocomplete="off"> <span class="error"></span> </div> <div> <input type="submit" value="登錄"> </div> </form> </div> <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);
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(