jQuery介紹
- jQuery是一個輕量級的、兼容多瀏覽器的JavaScript庫。
- jQuery使用戶能夠更方便地處理HTML Document、Events、實現動畫效果、方便地進行Ajax交互,能夠極大地簡化JavaScript編程。它的宗旨就是:“Write less, do more.“
前端模塊通常叫做 "類庫"
pycharm導入jQuery統一模板
注:此處使用CDN內容分發網絡(https://www.bootcdn.cn/),也可以在本地使用文件,需要每次拷貝文件在文件夾中
原生js對象和jQuery對象的區別與轉換
兩個對象之間方法不能混用!
$()[0] 轉化為原生js對象
$(js對象) 轉化為jQuery對象
JQuery基本語法結構
$(選擇器).action{屬性值}
原本的寫法
jQuery() <===> $()
使用jQuery注意事項:你一定要先通過script標簽引入jQuery代碼才能使用它的一系列方法
查找標簽:
1.基本選擇器
id選擇器:
$("#id")
標簽選擇器:
$("tagName")
class選擇器:
$(".className")
配合使用:
$("div.c1") // 找到有c1 class類的div標簽
所有元素選擇器:
$("*")
組合選擇器:
$("#id, .className, tagName")
2.層級選擇器:
x和y可以為任意選擇器
$("x y");// x的所有后代y(子子孫孫)
$("x > y");// x的所有兒子y(兒子)
$("x + y")// 找到所有緊挨在x后面的y
$("x ~ y")// x之后所有的兄弟y
3.基本篩選器:
: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標簽
自定義模態框

<!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> <style> .hidden { display: none; } .cover { position: fixed; top: 0; left: 0; right: 0; bottom: 0; background-color: rgba(128,128,128,0.4); } .modal { position: fixed; top: 50%; left: 50%; background-color: white; height: 200px; width: 400px; margin-left: -200px; margin-top: -100px; } </style> </head> <body> <div class="bottommmm">我是最底層的頁面 <button class="call">叫人</button> </div> <div class="cover hidden"></div> <div class="modal hidden"> <p>username:<input type="text"></p> <p>password:<input type="text"></p> <button class="cancel">滾蛋</button> </div> <script> var btnEle = $('.call')[0]; // 獲取原生js對象 var cancelEle = $('.cancel')[0]; btnEle.onclick = function () { // 將蓋板和模態框的hidden移除 $('.cover').removeClass('hidden'); // 移除類屬性 classList.remove() $('.modal').removeClass('hidden'); }; cancelEle.onclick = function () { // 給蓋板和模態框添加hidden屬性 $('.cover').addClass('hidden'); // 添加類屬性 classList.add() $('.modal').addClass('hidden'); } </script> </body> </html>
4.屬性選擇器:
[attribute]
[attribute=value]// 屬性等於
[attribute!=value]// 屬性不等於
例子:
// 示例 <input type="text"> <input type="password"> <input type="checkbox"> $("input[type='checkbox']");// 取到checkbox類型的input標簽 $("input[type!='text']");// 取到類型不是text的input標簽
5.表單篩選器:
: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
注意:checked查找時,默認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="item"> <div class="title">菜單一</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">菜單二</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">菜單三</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 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"); // jQuery鏈式操作 一行代碼實現需求 $(this).next().removeClass('hide').parent().siblings().find('.items').addClass('hide') }); </script> 左側菜單欄
注意:示例中使用鏈式操作,因為jQuery每次方法執行完后返回this對象,這樣后面的方法就可以繼續在this環境下執行
操作標簽
樣式操作
樣式類
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="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script> <style> .btn { height: 50px; width: 100px; border: 5px solid orange; position: fixed; right: 20px; bottom: 20px; } .hidden { display: none; } </style> </head> <body> <div style="height: 1000px;background-color: red"></div> <div style="height: 1000px;background-color: green"></div> <div style="height: 1000px;background-color: blue"></div> <div class="btn hidden">點我回到頂部 </div> <script> $(window).scroll(function () { if($(window).scrollTop() > 600){ $('.btn').removeClass('hidden') } }); $('.btn').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"])
獲取用戶上傳的文件對象,轉為JavaScript對象,用.files[0]取
示例:
獲取被選中的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="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script> </head> <body> <form action=""> <p>username: <input type="text" id="d1"> <span style="color: red"></span> </p> <p>password: <input type="password" id="d2"> <span style="color: red"></span> </p> <input type="button" id="btn" value="注冊"> </form> <script> $('#btn').click(function () { // 獲取用戶輸入的用戶名和密碼 var userNameVal = $('#d1').val(); var passWordVal = $('#d2').val(); // 依次判斷用戶名和密碼是否為空 if(userNameVal.length===0){ // 在username框后面的span標簽中添加提示信息 $('#d1').next().text('用戶名不能為空') } if(passWordVal.length===0){ $('#d2').next().text('密碼不能為空 你個大帥比') } }) </script> </body> </html>
屬性操作
用於ID等或自定義屬性:
attr(attrName)// 返回第一個匹配元素的屬性值
attr(attrName, attrValue)// 為所有匹配元素設置一個屬性值 例:$("a").attr('href',url) 修改a標簽鏈接為url
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")。
prop和attr的區別:
雖然都是屬性,但他們所指的屬性並不相同,attr所指的屬性是HTML標簽屬性,而prop所指的是DOM對象屬性,可以認為attr是顯式的,而prop是隱式的。
- 對於標簽上有的能看到的屬性和自定義屬性都用attr
- 對於返回布爾值的比如checkbox、radio和option的是否被選中都用prop。
文檔處理
添加到指定元素內部的后面
$(A).append(B)// 把B追加到A
$(A).appendTo(B)// 把A追加到B
示例:
<table id="follow_table" border="1" cellspacing="10" cellpadding="20"> <!-- 展示粉絲和關注者的表 --> <thead> <tr> <th>登錄名</th> <th>id</th> </tr> </thead> <tbody> </tbody> </table> <script> $('#followers_url').click(function () { // 點擊按鈕 var click_url = $("#followers_url button").text() //獲取按鈕的文字內容 $.getJSON(click_url, function (data) { // 請求地址獲取返回 $.each(data, function (i, item) { //遍歷返回列表中每個元素 $('#follow_table tbody').append( //插入為字符串插入,需要插入內容用字符串拼接形式 '<tr><td><p>'+ item.login + '</p></td>' + '<td><p>'+ item.id +'</p></td>' + '</tr>' ) }); }); }); </script>
添加到指定元素內部的前面
$(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="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script> <style> button { background-color: orange; height: 50px; width: 100px; } </style> </head> <body> <button id="d1">刀龍寶刀,點擊就送</button> <script> $('#d1').click(function () { // $(this).clone().insertAfter($(this)) // 單純的克隆 只會克隆標簽及樣式 不會克隆事件 $(this).clone(true).insertAfter($(this)) // 參數true 事件也克隆 }) </script> </body> </html>
注意:
clone() 單純的克隆 只會克隆標簽及樣式 不會克隆事件
clone(true) 參數true 事件也克隆
事件
常用事件
click(function(){...})
hover(function(){...})
blur(function(){...})
focus(function(){...})
change(function(){...})
keyup(function(){...})
點擊按鈕警告示例:

<!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> </head> <body> <p>ppp</p> <button>點我 證明我的清白</button> <script> $('button').on('click',function () { alert(123) }) // $('p').hover(function () { // alert(123) // }) // 兩種方式有時候一種不行就用另外一種 </script> </body> </html>
input框輸入控制台實時監聽:

<!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> </head> <body> <input type="text" id="d1"> <script> $('#d1').on('input',function () { console.log(this.value) }) </script> </body> </html>
事件綁定
.on( events [, selector ],function(){})
- events: 事件
- selector: 選擇器(可選的)
- function: 事件處理函數
移除事件
.off( events [, selector ][,function(){}])
off()
方法移除用 .on()
綁定的事件處理程序。
- events: 事件
- selector: 選擇器(可選的)
- function: 事件處理函數
阻止后續事件執行
return false; // 常見阻止表單提交等
- e.preventDefault();
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>阻止默認事件</title> <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script> </head> <body> <form action=""> <input type="submit" id="d1"> <span style="color: red"></span> </form> <script> $('#d1').click(function (e) { $('span').text('你好啊'); // 阻止標簽后續事件的運行 // 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> </head> <body> <div>div <p>p <span>span</span> </p> </div> <script> $('div').click(function (e) { alert('我是div') }); $('p').click(function (e) { alert('我是p'); e.stopPropagation() }); $('span').on('click',function (e) { alert('我是span'); // e.stopPropagation() // 阻止事件冒泡 }); </script> </body> </html>
頁面載入
onload 等待什么什么加載完畢之后再執行
當DOM載入就緒可以查詢及操縱時綁定一個要執行的函數。這是事件模塊中最重要的一個函數,因為它可以極大地提高web應用程序的響應速度。
兩種寫法:
$(document).ready(function(){
// 在這里寫你的JS代碼...
})
簡寫:
$(function(){
// 你在這里寫你的代碼
})
文檔加載完綁定事件,並且阻止默認事件發生:

<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <meta http-equiv="x-ua-compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>登錄注冊示例</title> <style> .error { color: red; } </style> </head> <body> <form id="myForm"> <label for="name">姓名</label> <input type="text" id="name"> <span class="error"></span> <label for="passwd">密碼</label> <input type="password" id="passwd"> <span class="error"></span> <input type="submit" id="modal-submit" value="登錄"> </form> <script src="jquery-3.2.1.min.js"></script> <script src="s7validate.js"></script> <script> function myValidation() { // 多次用到的jQuery對象存儲到一個變量,避免重復查詢文檔樹 var $myForm = $("#myForm"); $myForm.find(":submit").on("click", function () { // 定義一個標志位,記錄表單填寫是否正常 var flag = true; $myForm.find(":text, :password").each(function () { var val = $(this).val(); if (val.length <= 0 ){ var labelName = $(this).prev("label").text(); $(this).next("span").text(labelName + "不能為空"); flag = false; } }); // 表單填寫有誤就會返回false,阻止submit按鈕默認的提交表單事件 return flag; }); // input輸入框獲取焦點后移除之前的錯誤提示信息 $myForm.find("input[type!='submit']").on("focus", function () { $(this).next(".error").text(""); }) } // 文檔樹就緒后執行 $(document).ready(function () { myValidation(); }); </script> </body> </html>
與window.onload的區別
- window.onload()函數有覆蓋現象,必須等待着圖片資源加載完成之后才能調用
- jQuery的這個入口函數沒有函數覆蓋現象,文檔加載完成之后就可以調用(建議使用此函數)
事件委托
事件委托是通過事件冒泡的原理,利用父標簽去捕獲子標簽的事件。
示例:
表格中每一行的編輯和刪除按鈕都能觸發相應的事件。
$("table").on("click", ".delete", function () {
// 刪除按鈕綁定的事件
})
當設定完button按鈕后,script再添加button按鈕就無效,通過事件委托,即使后面自己添加button,也會擁有相同效果
<!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> </head> <body> <button>點我彈你</button> <button>點我彈你</button> <button>點我彈你</button> <script> // $('button').click(function () { // 讓所有的button都綁定點擊事件 // alert('123') // }) // 事件委托 將body內所有的點擊事件 委托給button按鈕 $('body').on('click','button',function () { alert('放假了') }) </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>
補充
each
1. $.each(可迭代對象,function(index,obj){})
2. $('div').each(fucntion(index,obj){})
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對應的數據