日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

jquery的操作

發(fā)布時間:2024/4/17 编程问答 36 豆豆
生活随笔 收集整理的這篇文章主要介紹了 jquery的操作 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

jQuery

jQuery介紹

  • jQuery是一個輕量級的、兼容多瀏覽器的JavaScript庫。
  • jQuery使用戶能夠更方便地處理HTML Document、Events、實現(xiàn)動畫效果、方便地進行Ajax交互,能夠極大地簡化JavaScript編程。它的宗旨就是:“Write less, do more.“
  • jQuery的優(yōu)勢

  • 一款輕量級的JS框架。jQuery核心js文件才幾十kb,不會影響頁面加載速度。
  • 豐富的DOM選擇器,jQuery的選擇器用起來很方便,比如要找到某個DOM對象的相鄰元素,JS可能要寫好幾行代碼,而jQuery一行代碼就搞定了,再比如要將一個表格的隔行變色,jQuery也是一行代碼搞定。
  • 鏈?zhǔn)奖磉_式。jQuery的鏈?zhǔn)讲僮骺梢园讯鄠€操作寫在一行代碼里,更加簡潔。
  • 事件、樣式、動畫支持。jQuery還簡化了js操作css的代碼,并且代碼的可讀性也比js要強。
  • Ajax操作支持。jQuery簡化了AJAX操作,后端只需返回一個JSON格式的字符串就能完成與前端的通信。
  • 跨瀏覽器兼容。jQuery基本兼容了現(xiàn)在主流的瀏覽器,不用再為瀏覽器的兼容問題而傷透腦筋。
  • 插件擴展開發(fā)。jQuery有著豐富的第三方的插件,例如:樹形菜單、日期控件、圖片切換插件、彈出窗口等等基本前端頁面上的組件都有對應(yīng)插件,并且用jQuery插件做出來的效果很炫,并且可以根據(jù)自己需要去改寫和封裝插件,簡單實用。
  • jQuery內(nèi)容:

  • 選擇器
  • 篩選器
  • 樣式操作
  • 文本操作
  • 屬性操作
  • 文檔處理
  • 事件
  • 動畫效果
  • 插件
  • each、data、Ajax
  • 下載鏈接:jQuery官網(wǎng)

    中文文檔: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端用戶已經(jīng)逐步被移動端用戶所取代,如果沒有特殊要求的話,一般都會選擇放棄對678的支持。

    jQuery對象

    jQuery對象就是通過jQuery包裝DOM對象后產(chǎn)生的對象。jQuery對象是 jQuery獨有的。如果一個對象是 jQuery對象,那么它就可以使用jQuery里的方法:例如$(“#i1”).html()。

    $("#i1").html()的意思是:獲取id值為 i1的元素的html代碼。其中 html()是jQuery里的方法。

    相當(dāng)于: document.getElementById("i1").innerHTML;

    雖然 jQuery對象是包裝 DOM對象后產(chǎn)生的,但是 jQuery對象無法使用 DOM對象的任何方法,同理 DOM對象也沒不能使用 jQuery里的方法。

    一個約定,我們在聲明一個jQuery對象變量的時候在變量名前面加上$:

    var $variable = jQuery對像 var variable = DOM對象 $variable[0]//jQuery對象轉(zhuǎn)成DOM對象

    拿上面那個例子舉例,jQuery對象和DOM對象的使用:

    $("#i1").html();//jQuery對象可以使用jQuery的方法 $("#i1")[0].innerHTML;// DOM對象使用DOM的方法

    jQuery基礎(chǔ)語法

    $(selector).action()

    查找標(biāo)簽

    基本選擇器

    id選擇器:

    $("#id")

    標(biāo)簽選擇器:

    $("tagName")

    class選擇器:

    $(".className")

    配合使用:

    $("div.c1") // 找到有c1 class類的div標(biāo)簽

    所有元素選擇器:

    $("*")

    組合選擇器:

    $("#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 // 匹配所有索引值為偶數(shù)的元素,從 0 開始計數(shù) :odd // 匹配所有索引值為奇數(shù)的元素,從 0 開始計數(shù) :gt(index)// 匹配所有大于給定索引值的元素 :lt(index)// 匹配所有小于給定索引值的元素 :not(元素選擇器)// 移除所有滿足not條件的標(biāo)簽 :has(元素選擇器)// 選取所有包含一個或多個標(biāo)簽在其內(nèi)的標(biāo)簽(指的是從后代元素找)

    例子:

    $("div:has(h1)")// 找到所有后代中有h1標(biāo)簽的div標(biāo)簽 $("div:has(.c1)")// 找到所有后代中有c1樣式類的div標(biāo)簽 $("li:not(.c1)")// 找到所有不包含c1樣式類的li標(biāo)簽 $("li:not(:has(a))")// 找到所有后代中不含a標(biāo)簽的li標(biāo)簽

    練習(xí):

    自定義模態(tài)框,使用jQuery實現(xiàn)彈出和隱藏功能。

    <!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>自定義模態(tài)框</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="關(guān)閉"> </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版自定義模態(tài)框

    屬性選擇器:

    [attribute] [attribute=value]// 屬性等于 [attribute!=value]// 屬性不等于

    例子:

    // 示例 <input type="text"> <input type="password"> <input type="checkbox"> $("input[type='checkbox']");// 取到checkbox類型的input標(biāo)簽 $("input[type!='text']");// 取到類型不是text的input標(biāo)簽

    表單篩選器

    :text :password
    :file :radio :checkbox
    :submit :reset :button

    例子:

    $(":checkbox") // 找到所有的checkbox

    表單對象屬性:

    :enabled :disabled :checked :selected

    例子:

    找到可用的input標(biāo)簽

    <form><input name="email" disabled="disabled" /><input name="id" /> </form> $("input:enabled") // 找到可用的input標(biāo)簽

    ?找到被選中的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() // 查找當(dāng)前元素的所有的父輩元素
    $("#id").parentsUntil() // 查找當(dāng)前元素的所有的父輩元素,直到遇到匹配的那個元素為止。

    兒子和兄弟元素:

    $("#id").children();// 兒子們 $("#id").siblings();// 兄弟們

    查找

    搜索所有與指定表達式匹配的元素。這個函數(shù)是找出正在處理的元素的后代元素的好方法。

    $("div").find("p")

    等價于$("div p")

    篩選

    篩選出與指定表達式匹配的元素集合。這個方法用于縮小匹配的范圍。用逗號分隔多個表達式。

    $("div").filter(".c1") // 從結(jié)果集中過濾出有c1樣式類的

    等價于 $("div.c1")

    補充:

    .first() // 獲取匹配的第一個元素 .last() // 獲取匹配的最后一個元素 .not() // 從匹配元素的集合中刪除與指定表達式匹配的元素 .has() // 保留包含特定后代的元素,去掉那些不含有指定后代的元素。 .eq() // 索引值等于指定值的元素

    示例:左側(cè)菜單

    <!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>左側(cè)菜單示例</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的標(biāo)簽 $(".items").addClass("hide"); //批量操作 $(this).next().removeClass("hide");}); </script> 左側(cè)菜單示例

    操作標(biāo)簽

    樣式操作

    樣式類

    addClass();// 添加指定的CSS類名。 removeClass();// 移除指定的CSS類名。 hasClass();// 判斷樣式存不存在 toggleClass();// 切換CSS類名,如果有就移除,如果沒有就添加。

    示例:開關(guān)燈和模態(tài)框

    CSS

    css("color","red")//DOM操作:tag.style.color="red"

    示例:

    $("p").css("color", "red"); //將所有p標(biāo)簽的字體設(shè)置為紅色

    位置操作

    offset()// 獲取匹配元素在當(dāng)前窗口的相對偏移或設(shè)置元素位置 position()// 獲取匹配元素相對父元素的偏移 scrollTop()// 獲取匹配元素相對滾動條頂部的偏移 scrollLeft()// 獲取匹配元素相對滾動條左側(cè)的偏移

    .offset()方法允許我們檢索一個元素相對于文檔(document)的當(dāng)前位置。

    .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>位置相關(guān)示例之返回頂部</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內(nèi)容 html(val)// 設(shè)置所有匹配元素的html內(nèi)容

    文本值:

    text()// 取得所有匹配元素的內(nèi)容 text(val)// 設(shè)置所有匹配元素的內(nèi)容

    值:

    val()// 取得第一個匹配元素的當(dāng)前值 val(val)// 設(shè)置所有匹配元素的值 val([val1, val2])// 設(shè)置多選的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>

    設(shè)置值:

    $("[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)// 為所有匹配元素設(shè)置一個屬性值 attr({k1: v1, k2:v2})// 為所有匹配元素設(shè)置多個屬性值 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的區(qū)別:

    attr全稱attribute(屬性)?

    prop全稱property(屬性)

    雖然都是屬性,但他們所指的屬性并不相同,attr所指的屬性是HTML標(biāo)簽屬性,而prop所指的是DOM對象屬性,可以認為attr是顯式的,而prop是隱式的。

    舉個例子:

    <input type="checkbox" id="i1" value="1">

    針對上面的代碼,

    $("#i1").attr("checked") // undefined $("#i1").prop("checked") // false

    可以看到attr獲取一個標(biāo)簽內(nèi)沒有的東西會得到undefined,而prop獲取的是這個DOM對象的屬性,因此checked為false。

    如果換成下面的代碼:

    <input type="checkbox" checked id="i1" value="1">

    再執(zhí)行:

    $("#i1").attr("checked") // checked $("#i1").prop("checked") // true

    這已經(jīng)可以證明attr的局限性,它的作用范圍只限于HTML標(biāo)簽內(nèi)的屬性,而prop獲取的是這個DOM對象的屬性,選中返回true,沒選中返回false。

    接下來再看一下針對自定義屬性,attr和prop又有什么區(qū)別:

    <input type="checkbox" checked id="i1" value="1" me="自定義屬性">

    執(zhí)行以下代碼:

    $("#i1").attr("me") // "自定義屬性" $("#i1").prop("me") // undefined

    可以看到prop不支持獲取標(biāo)簽的自定義屬性。

    總結(jié)一下:

  • 對于標(biāo)簽上有的能看到的屬性和自定義屬性都用attr
  • 對于返回布爾值的比如checkbox、radio和option的是否被選中都用prop。
  • ?

    練習(xí)題:全選、反選、取消

    文檔處理

    添加到指定元素內(nèi)部的后面

    $(A).append(B)// 把B追加到A $(A).appendTo(B)// 把A追加到B

    添加到指定元素內(nèi)部的前面

    $(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()// 刪除匹配的元素集合中所有的子節(jié)點。

    例子:

    點擊按鈕在表格添加一行數(shù)據(jù)。

    點擊每一行的刪除按鈕刪除當(dāng)前行數(shù)據(jù)。

    替換

    replaceWith() replaceAll()

    克隆

    clone()// 參數(shù)

    克隆示例:

    <!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方法不加參數(shù)true,克隆標(biāo)簽但不克隆標(biāo)簽帶的事件 $("#b1").on("click", function () {$(this).clone().insertAfter(this);});// clone方法加參數(shù)true,克隆標(biāo)簽并且克隆標(biāo)簽帶的事件 $("#b2").on("click", function () {$(this).clone(true).insertAfter(this);}); </script> </body> </html> 點擊復(fù)制按鈕

    事件

    常用事件

    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標(biāo)簽的值發(fā)生變化的時候 $("select").change(function (event) {// 如果shift按鍵被按下,就進入批量編輯模式// shift按鍵對應(yīng)的code是16// 判斷當(dāng)前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. 取到當(dāng)前select選中的值var value = $(this).val();// 2. 給其他被選中行的select設(shè)置成和我一樣的值// 2.1 找到那些被選中行的selectvar $select = $("input:checked").parent().parent().find("select")// 2.2 給選中的select賦值 $select.val(value);}}); </script> </body> </html> 按住shift實現(xiàn)批量操作

    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事件

    實時監(jiān)聽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>實時監(jiān)聽input輸入值變化</title> </head> <body> <input type="text" id="i1"><script src="jquery-3.2.1.min.js"></script> <script>/** oninput是HTML5的標(biāo)準(zhǔn)事件* 能夠檢測textarea,input:text,input:password和input:search這幾個元素的內(nèi)容變化,* 在內(nèi)容修改后立即被觸發(fā),不像onchange事件需要失去焦點才觸發(fā)* oninput事件在IE9以下版本不支持,需要使用IE特有的onpropertychange事件替代* 使用jQuery庫的話直接使用on同時綁定這兩個事件即可。* */$("#i1").on("input propertychange", function () {alert($(this).val());}) </script> </body> </html> input值變化事件

    事件綁定

  • .on( events [, selector ],function(){})
    • events: 事件
    • selector: 選擇器(可選的)
    • function: 事件處理函數(shù)

    移除事件

  • .off( events [, selector ][,function(){}])
  • off() 方法移除用?.on()綁定的事件處理程序。

    • events: 事件
    • selector: 選擇器(可選的)
    • function: 事件處理函數(shù)

    阻止后續(xù)事件執(zhí)行

  • return?false;?// 常見阻止表單提交等
  • e.preventDefault();
  • <!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><title>阻止默認事件</title> </head> <body><form action=""><button id="b1">點我</button> </form><script src="jquery-3.3.1.min.js"></script> <script>$("#b1").click(function (e) {alert(123);//return false; e.preventDefault();}); </script> </body> </html>

    ?

    注意:

    像click、keydown等DOM中定義的事件,我們都可以使用`.on()`方法來綁定事件,但是`hover`這種jQuery中定義的事件就不能用`.on()`方法來綁定了。

    想使用事件委托的方式綁定hover事件處理函數(shù),可以參照如下代碼分兩步綁定事件:

    $('ul').on('mouseenter', 'li', function() {//綁定鼠標(biāo)進入事件$(this).addClass('hover'); }); $('ul').on('mouseleave', 'li', function() {//綁定鼠標(biāo)劃出事件$(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>

    頁面載入

    當(dāng)DOM載入就緒可以查詢及操縱時綁定一個要執(zhí)行的函數(shù)。這是事件模塊中最重要的一個函數(shù),因為它可以極大地提高web應(yīng)用程序的響應(yīng)速度。

    兩種寫法:

    $(document).ready(function(){ // 在這里寫你的JS代碼... })

    簡寫:

    $(function(){ // 你在這里寫你的代碼 })

    文檔加載完綁定事件,并且阻止默認事件發(fā)生:

    <!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對象存儲到一個變量,避免重復(fù)查詢文檔樹var $myForm = $("#myForm");$myForm.find(":submit").on("click", function () {// 定義一個標(biāo)志位,記錄表單填寫是否正常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("");})}// 文檔樹就緒后執(zhí)行 $(document).ready(function () {myValidation();}); </script> </body> </html> 登錄校驗示例

    事件委托

    事件委托是通過事件冒泡的原理,利用父標(biāo)簽去捕獲子標(biāo)簽的事件。

    示例:

    表格中每一行的編輯和刪除按鈕都能觸發(fā)相應(yīng)的事件。

    $("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)):

    描述:一個通用的迭代函數(shù),它可以用來無縫迭代對象和數(shù)組。數(shù)組和類似數(shù)組的對象通過一個長度屬性(如一個函數(shù)的參數(shù)對象)來迭代數(shù)字索引,從0到length - 1。其他對象通過其屬性名進行迭代。

    li =[10,20,30,40] $.each(li,function(i, v){console.log(i, v);//index是索引,ele是每次循環(huán)的具體元素。 })

    輸出:

    010 120 230 340

    .each(function(index, Element)):

    描述:遍歷一個jQuery對象,為每個匹配元素執(zhí)行一個函數(shù)。

    .each() 方法用來迭代jQuery對象中的每一個DOM元素。每次回調(diào)函數(shù)執(zhí)行時,會傳遞當(dāng)前循環(huán)次數(shù)作為參數(shù)(從0開始計數(shù))。由于回調(diào)函數(shù)是在當(dāng)前DOM元素為上下文的語境中觸發(fā)的,所以關(guān)鍵字 this 總是指向這個元素。

    // 為每一個li標(biāo)簽添加foo $("li").each(function(){$(this).addClass("c1"); });

    注意: jQuery的方法返回一個jQuery對象,遍歷jQuery集合中的元素 - 被稱為隱式迭代的過程。當(dāng)這種情況發(fā)生時,它通常不需要顯式地循環(huán)的 .each()方法:

    也就是說,上面的例子沒有必要使用each()方法,直接像下面這樣寫就可以了:

    $("li").addClass("c1"); // 對所有標(biāo)簽做統(tǒng)一操作

    注意:

    在遍歷過程中可以使用 return?false提前結(jié)束each循環(huán)。

    終止each循環(huán)

    return false

    伏筆...

    .data()

    在匹配的元素集合中的所有元素上存儲任意相關(guān)數(shù)據(jù)或返回匹配的元素集合中的第一個元素的給定名稱的數(shù)據(jù)存儲的值。

    .data(key, value):

    描述:在匹配的元素上存儲任意相關(guān)數(shù)據(jù)。

    $("div").data("k",100);//給所有div標(biāo)簽都保存一個名為k,值為100

    .data(key):

    描述: 返回匹配的元素集合中的第一個元素的給定名稱的數(shù)據(jù)存儲的值—通過 .data(name, value)HTML5 data-*屬性設(shè)置。

    $("div").data("k");//返回第一個div標(biāo)簽中保存的"k"的值

    .removeData(key):

    描述:移除存放在元素上的數(shù)據(jù),不加key參數(shù)表示移除所有保存的數(shù)據(jù)。

    $("div").removeData("k"); //移除元素上存放k對應(yīng)的數(shù)據(jù)

    示例:

    模態(tài)框編輯的數(shù)據(jù)回填表格

    插件(了解即可)

    jQuery.extend(object)

    jQuery的命名空間下添加新的功能。多用于插件開發(fā)者向 jQuery 中添加新函數(shù)時使用。

    示例:

    <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)

    一個對象的內(nèi)容合并到j(luò)Query的原型,以提供新的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() {// 定義一個標(biāo)志位,表示驗證通過還是驗證不通過var flag = true;var errMsg;// 校驗規(guī)則$("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("");}// 上面都是我定義的工具函數(shù) $.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) {// 定義一個標(biāo)志位,表示驗證通過還是驗證不通過var flag = true;var errMsg;// 校驗規(guī)則$("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("");}// 上面都是我定義的工具函數(shù) $.extend({validate: function (arg) {$("form :submit").on("click", function () {return check(arg);});$("form :input[type!='submit']").on("focus", function () {clearError(this);});}}); })(jQuery); JS文件

    課后習(xí)題:

  • 登錄+驗證
  • 左側(cè)菜單
  • 表格-增、刪、改、查
  • 轉(zhuǎn)載于:https://www.cnblogs.com/huningfei/p/9693252.html

    總結(jié)

    以上是生活随笔為你收集整理的jquery的操作的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。