jQuery知識梳理20190818

来源:https://www.cnblogs.com/itzhouq/archive/2019/08/21/jQuery2.html
-Advertisement-
Play Games

jQuery知識梳理20190818 [TOC] 1. 時間綁定和解綁 2. 區別mouseover與mouseenter 3. 時間委托(委派/代理) 4 . 多庫共存 如果有2個庫都有$, 就存在衝突。 jQuery庫可以釋放$的使用權, 讓另一個庫可以正常使用, 此時jQuery庫只能使用jQ ...


目錄

jQuery知識梳理20190818

1. 時間綁定和解綁

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>18_事件綁定與解綁</title>
</head>
<style type="text/css">
  * {
    margin: 0px;
  }
  .out {
    position: absolute;
    width: 200px;
    height: 200px;
    top: 20px;
    left: 10px;
    background: blue;
  }
  .inner {
    position: absolute;
    width: 100px;
    height: 100px;
    top: 50px;
    background: red;
  }
  .divBtn {
    position: absolute;
    top: 250px;
  }
</style>
<body style="height: 2000px;">
<div class="out">
  外部DIV
  <div class="inner">內部div</div>
</div>
<div class='divBtn'>
  <button id="btn1">取消綁定所有事件</button>
  <button id="btn2">取消綁定mouseover事件</button>
  <button id="btn3">測試事件坐標</button>
  <a href="http://www.baidu.com" id="test4">百度一下</a>
</div>

<!--
1. 事件綁定(2種):
  * eventName(function(){})
    綁定對應事件名的監聽, 例如:$('#div').click(function(){});
  * on(eventName, funcion(){})
    通用的綁定事件監聽, 例如:$('#div').on('click', function(){})
  * 優缺點:
    eventName: 編碼方便, 但只能加一個監聽, 且有的事件監聽不支持
    on: 編碼不方便, 可以添加多個監聽, 且更通用
2. 事件解綁:
  * off(eventName)
3. 事件的坐標
  * event.clientX, event.clientY  相對於視口的左上角
  * event.pageX, event.pageY  相對於頁面的左上角
  * event.offsetX, event.offsetY 相對於事件元素左上角
4. 事件相關處理
  * 停止事件冒泡 : event.stopPropagation()
  * 阻止事件預設行為 : event.preventDefault()
-->
<script src="js/jquery-1.10.1.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
  $(function () {
    // 1.給class為out的div的點擊事件綁定監聽函數,列印'out clicked'(用兩種方法綁定)
    /*$('.out').click(function () {
      console.log('out click1')
    })*/
    $('.out').on('click', function () {
      console.log('out clicked2')
    })

    //2.給class為inner的div的滑鼠移入和滑鼠移出事件綁定監聽函數
    /*$('.inner')
      .mouseenter(function () {
        console.log('進入...')
      })
      .mouseleave(function () {
        console.log('離開...')
      })*/
    $('.inner')
      .on('mouseenter', function () {
        console.log('進入...')
      })
      .on('mouseleave', function () {
        console.log('離開...')
      })
    /*$('.inner').hover(function () {
      console.log('進入...')
    }, function () {
      console.log('離開...')
    })*/

    //3. 點擊btn1解除inner上的所有事件監聽
    $('#btn1').click(function () {
      $('.inner').off()
    })

    //4.點擊btn2解除inner上的mouseover事件
    $('#btn2').click(function () {
      $('.inner').off('mouseover')
    })

    //5. 點擊btn3得到事件坐標
    $('#btn3').click(function (event) { // event時間對象
      console.log(event.offsetX, event.offsetY) // 原點為時間元素的左上角
      console.log(event.clientX, event.clientY) // 原點為視窗的左上角
      console.log(event.pageX, event.pageY) // 原點為頁面的左上角
    })

    //6. 點擊.inner區域, 外部點擊監聽不響應
    $('.inner').click(function (event) {
      console.log('click inner')
      // 停止事件冒泡
      event.stopPropagation()
    })

    //7. 點擊鏈接, 如果當前時間是偶數不跳轉
    $('#test4').click(function () {
      var time = Date.now(event)
      alert(time)
      if(time%2===0) {
        // 阻止事件預設行為
        event.preventDefault()
      }
    })
  })
</script>
</body>
</html>

2. 區別mouseover與mouseenter

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>19_事件切換</title>
</head>
<style type="text/css">
    * {
        margin: 0px;
    }
    .div1 {
        position: absolute;
        width: 200px;
        height: 200px;
        top: 50px;
        left: 10px;
        background: olive;
    }
    .div2 {
        position: absolute;
        width: 100px;
        height: 100px;
        top: 50px;
        background: red;
    }
    .div3 {
        position: absolute;
        width: 200px;
        height: 200px;
        top: 50px;
        left: 230px;
        background: olive;
    }
    .div4 {
        position: absolute;
        width: 100px;
        height: 100px;
        top: 50px;
        background: yellow;
    }
    .divText{
        position: absolute;
        top: 330px;
        left: 10px;
    }
</style>
<body>
<div class="divText">
    區分滑鼠的事件
</div>
<div class="div1">
    div1.....
    <div class="div2">div2....</div>
</div>
<div class="div3">
    div3.....
    <div class="div4">div4....</div>
</div>
<!--
區別mouseover與mouseenter?
* mouseover: 在移入子元素時也會觸發, 對應mouseout
* mouseenter: 只在移入當前元素時才觸發, 對應mouseleave
hover()使用的就是mouseenter()和mouseleave()
-->
<script src="js/jquery-1.10.1.js" type="text/javascript"></script>
<script type="text/javascript">
    $('.div1').mouseover(function () {
        console.log('移入div1或其子元素')
    }).mouseout(function () {
        console.log('移出div1或其子元素')
    })

    $('.div3').mouseenter(function () {
        console.log('移入div3元素')
    }).mouseleave(function () {
        console.log('移出div3元素')
    })

    $('.div3').hover(function () {
        console.log('移入div33元素')
        this.style.background = 'red'
    }, function () {
        console.log('移出div33元素')
        this.style.background = 'blue'
    })
</script>
</body>
</html>

3. 時間委托(委派/代理)

<!DOCTYPE HTML>
<html>
<head>
  <meta charset="UTF-8">
  <title>20_事件委托2</title>
</head>
<body>
<ul>
  <li>1111</li>
  <li>2222</li>
  <li>3333</li>
  <li>4444</li>
</ul>
<li>22222</li><br>
<button id="btn1">添加新的li</button>
<button id="btn2">刪除ul上的事件委托的監聽器</button>

<!--
1. 事件委托(委派/代理):
  * 將多個子元素(li)的事件監聽委托給父輩元素(ul)處理
  * 監聽回調是加在了父輩元素上
  * 當操作任何一個子元素(li)時, 事件會冒泡到父輩元素(ul)
  * 父輩元素不會直接處理事件, 而是根據event.target得到發生事件的子元素(li), 通過這個子元素調用事件回調函數
2. 事件委托的2方:
  * 委托方: 業主  li
  * 被委托方: 中介  ul
3. 使用事件委托的好處
  * 添加新的子元素, 自動有事件響應處理
  * 減少事件監聽的數量: n==>1
4. jQuery的事件委托API
  * 設置事件委托: $(parentSelector).delegate(childrenSelector, eventName, callback)
  * 移除事件委托: $(parentSelector).undelegate(eventName)
-->
<script src="js/jquery-1.10.1.js"></script>
<script>
  $(function () {
    //事件委托
    $('ul').delegate('li', 'click', function () {
            console.log(this) // 點擊發生事件的li
      this.style.background = 'red'
    })

    $('#btn1').click(function () {
      $('ul').append('<li>xxxxxxxxx</li>')
    })

    $('#btn2').click(function () {
      // 移除事件委托
      $('ul').undelegate()
    })
  })
</script>
</body>
</html>

4 . 多庫共存

如果有2個庫都有$, 就存在衝突。 jQuery庫可以釋放$的使用權, 讓另一個庫可以正常使用, 此時jQuery庫只能使用jQuery了。

 jQuery.noConflict()

5.window.onload$(document).ready()的區別

  • window.onload:包括頁面的圖片載入完後才會回調(晚), 只能有一個監聽回調。
  • $(document).ready():等同於: $(function(){}), 頁面載入完就回調(早),可以有多個監聽回調。

6. 自定義插件

  • 擴展jQuery的工具方法:$.extend(obj)
jQuery.extend({
  min: function(a, b) { return a < b ? a : b; },
  max: function(a, b) { return a > b ? a : b; }
});
  • 擴展jQuery對象的方法:$.fn.extend(object)
jQuery.fn.extend({
  check: function() {
    return this.each(function() { this.checked = true; });
  },
  uncheck: function() {
    return this.each(function() { this.checked = false; });
  }
});

  • 自定義文件:my_jQuery_plugin.js
/*
 擴展jQuery的工具方法 : $.extend(object)
   min(a, b) : 返回較小的值
   max(c, d) : 返回較大的值
   leftTrim() : 去掉字元串左邊的空格
   rightTrim() : 去掉字元串右邊的空格
 */

//正則
/*
 ^   匹配字元串開始
 \s  匹配空格
 +   匹配一次或者多次
 $   匹配字元串的末尾
 */
//擴展$ 
$.extend({
  min: function (a, b) {
    return (a < b) ? a : b
  },
  max: function (a, b) {
    return (a > b) ? a : b
  },
  leftTrim: function (strToBeTrimed) {
    return strToBeTrimed.replace(/^\s+/, '')
  },
  rightTrim: function (strToBeTrimed) {
    return strToBeTrimed.replace(/\s+$/, '')
  }
})

//擴展 $('#id').XXXXX
//$.fn.extend(object)
// checkAll() : 全選
// unCheckAll() : 全不選
// reverseCheck() : 全反選
$.fn.extend({
  checkAll: function () {
    // console.log('checkAll')
    this.prop('checked', true)
  },
  unCheckAll: function () {
    this.prop('checked', false)
  },
  reverseCheck: function () {
    this.each(function () {
      this.checked = !this.checked
    })
  }
})
  • 使用自定義插件
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>25_擴展插件</title>
  <style type="text/css">
    * {
      margin: 0px;
    }
    .div1 {
      position: absolute;
      width: 100px;
      height: 100px;
      top: 50px;
      left: 10px;
      background: red;
    }
  </style>
</head>
<body>
<input type="checkbox" name="items" value="足球"/>足球
<input type="checkbox" name="items" value="籃球"/>籃球
<input type="checkbox" name="items" value="羽毛球"/>羽毛球
<input type="checkbox" name="items" value="乒乓球"/>乒乓球
<br/>
<input type="button" id="checkedAllBtn" value="全 選"/>
<input type="button" id="checkedNoBtn" value="全不選"/>
<input type="button" id="reverseCheckedBtn" value="反選"/>
<!--
1. 擴展jQuery的工具方法
  $.extend(object)
2. 擴展jQuery對象的方法
  $.fn.extend(object)
-->
<script src="js/jquery-1.10.1.js" type="text/javascript"></script>
<script src="js/my_jQuery_plugin.js" type="text/javascript"></script>
<script type="text/javascript">
  /*
   需求:
   1. 給 $ 添加4個工具方法:
     * min(a, b) : 返回較小的值
     * max(c, d) : 返回較大的值
     * leftTrim() : 去掉字元串左邊的空格
     * rightTrim() : 去掉字元串右邊的空格
   2. 給jQuery對象 添加3個功能方法:
     * checkAll() : 全選
     * unCheckAll() : 全不選
     * reverseCheck() : 全反選
   */
  // 得到最大最小值
  var a = 1
  var b = 2
  var result_min = $.min(a, b)
  var result_max = $.max(a, b)
  console.log(result_min)
  console.log(result_max)

  // 左trim 右trim
  var str = '   悟空    '
  console.log('|' + str + '|')
  var resultStrLeft = $.leftTrim(str)
  console.log('|' + resultStrLeft + '|')
  var resultStrRight = $.rightTrim(str)
  console.log('|' + resultStrRight + '|')

  //全選
  $('#checkedAllBtn').click(function () {
    $(':checkbox').checkAll()
  })
  //全不選
  $('#checkedNoBtn').click(function () {
    $(':checkbox').unCheckAll()
  })
  //反選
  $('#reverseCheckedBtn').click(function () {
    $(':checkbox').reverseCheck()
  })
</script>
</body>
</html>

7. 使用插件

  • 插件是基於jQuery編寫的擴展庫。jQuery官網上有很多插件:http://plugins.jquery.com/
  • 常見插件:
    • 表單校驗插件:jquery-validation
    • jquery UI
    • 日期插件:laydate
  • 根據文檔和demo使用插件


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 在學習vue之前,我們應瞭解一下什麼是vue.js? 什麼是Vue.js? Vue.js是目前最後一個前端框架,React是最流行的一個前端框架(react除了開髮網站,還可以開發手機App,Vue語法也是可以進行手機App,還需要藉助 weex) Vue.js是前端的主流框架之一,和angular ...
  • 關於 new 運算符的原理: 1、紅寶書上解釋: (1)創建一個新對象 (2)將構造函數的作用域賦給新對象 (3)執行構造函數中的代碼 (4)返回新對象 2、MDN上的解釋: (1)一個繼承自 Foo.prototype 的新對象被創建 (2)使用指定的參數調用構造函數 Foo,並將 this 綁定 ...
  • //直接在input標簽內加入下麵兩個事件處理程式即可 onkeyup="this.value=this.value.replace(/\D|^0/g,'')" onafterpaste="this.value=this.value.replace(/\D|^0/g,'')" ...
  • 前言 項目中需要根據坐標定位,將自己的實現過程寫下來,廢話不多說,上代碼 正文 總結 ...
  • 前言 帶你走進高德api 正文 高德api地址:https://lbs.amap.com/ 1、註冊/登錄 2、進入應用管理創建應用並申請key 3、在項目中使用 效果圖 ...
  • 通過配置nginx幹掉 304 (from memory cache) (from disk cache) ...
  • 在日常工作中,我們需要將匹配到的所有路由,映射到一個組件上。 如下代碼想要達到的效果: 不傳page和id,則映射到user預設list頁面 傳page和id,根據page不同,顯示不同的頁面 問題 使用以下代碼片段是不能實現以上效果的,因為預設情況下page和id參數是必傳的,如果不傳參數,則會根 ...
  • DOM事件,就是瀏覽器或用戶針對頁面可以做出的某種動作,我們稱這些動作為DOM事件。它是用戶和頁面交互的核心。當動作發生(事件觸發)時,我們可以為其綁定一個或多個事件處理程式(函數),來完成我們想要實現的功能。 為了方便理解下麵即將要講解的內容,在正式開始之前,讓我們先來瞭解一個最常用的事件:cli ...
一周排行
    -Advertisement-
    Play Games
  • 概述:本文代碼示例演示瞭如何在WPF中使用LiveCharts庫創建動態條形圖。通過創建數據模型、ViewModel和在XAML中使用`CartesianChart`控制項,你可以輕鬆實現圖表的數據綁定和動態更新。我將通過清晰的步驟指南包括詳細的中文註釋,幫助你快速理解並應用這一功能。 先上效果: 在 ...
  • openGauss(GaussDB ) openGauss是一款全面友好開放,攜手伙伴共同打造的企業級開源關係型資料庫。openGauss採用木蘭寬鬆許可證v2發行,提供面向多核架構的極致性能、全鏈路的業務、數據安全、基於AI的調優和高效運維的能力。openGauss深度融合華為在資料庫領域多年的研 ...
  • openGauss(GaussDB ) openGauss是一款全面友好開放,攜手伙伴共同打造的企業級開源關係型資料庫。openGauss採用木蘭寬鬆許可證v2發行,提供面向多核架構的極致性能、全鏈路的業務、數據安全、基於AI的調優和高效運維的能力。openGauss深度融合華為在資料庫領域多年的研 ...
  • 概述:本示例演示了在WPF應用程式中實現多語言支持的詳細步驟。通過資源字典和數據綁定,以及使用語言管理器類,應用程式能夠在運行時動態切換語言。這種方法使得多語言支持更加靈活,便於維護,同時提供清晰的代碼結構。 在WPF中實現多語言的一種常見方法是使用資源字典和數據綁定。以下是一個詳細的步驟和示例源代 ...
  • 描述(做一個簡單的記錄): 事件(event)的本質是一個委托;(聲明一個事件: public event TestDelegate eventTest;) 委托(delegate)可以理解為一個符合某種簽名的方法類型;比如:TestDelegate委托的返回數據類型為string,參數為 int和 ...
  • 1、AOT適合場景 Aot適合工具類型的項目使用,優點禁止反編 ,第一次啟動快,業務型項目或者反射多的項目不適合用AOT AOT更新記錄: 實實在在經過實踐的AOT ORM 5.1.4.117 +支持AOT 5.1.4.123 +支持CodeFirst和非同步方法 5.1.4.129-preview1 ...
  • 總說周知,UWP 是運行在沙盒裡面的,所有許可權都有嚴格限制,和沙盒外交互也需要特殊的通道,所以從根本杜絕了 UWP 毒瘤的存在。但是實際上 UWP 只是一個應用模型,本身是沒有什麼許可權管理的,許可權管理全靠 App Container 沙盒控制,如果我們脫離了這個沙盒,UWP 就會放飛自我了。那麼有沒... ...
  • 目錄條款17:讓介面容易被正確使用,不易被誤用(Make interfaces easy to use correctly and hard to use incorrectly)限制類型和值規定能做和不能做的事提供行為一致的介面條款19:設計class猶如設計type(Treat class de ...
  • title: 從零開始:Django項目的創建與配置指南 date: 2024/5/2 18:29:33 updated: 2024/5/2 18:29:33 categories: 後端開發 tags: Django WebDev Python ORM Security Deployment Op ...
  • 1、BOM對象 BOM:Broswer object model,即瀏覽器提供我們開發者在javascript用於操作瀏覽器的對象。 1.1、window對象 視窗方法 // BOM Browser object model 瀏覽器對象模型 // js中最大的一個對象.整個瀏覽器視窗出現的所有東西都 ...