首頁 web前端 js教程 jQuery事件綁定用法詳解(附bind和live的區別)_jquery

jQuery事件綁定用法詳解(附bind和live的區別)_jquery

May 16, 2016 pm 03:19 PM
jquery 事件 綁定

This article analyzes the usage of jQuery event binding with examples. Share it with everyone for your reference, the details are as follows:

html:

<a href="#" onclick="addBtn()">addBtn</a>
<div id="mDiv">
  <button class="cBtn" onclick="alert(11111)">button1</button>
  <button class="cBtn">button2</button>
  <button class="cBtn">button3</button>
</div>

登入後複製

javascript:

<script type="text/javascript">
 function addBtn(){
   $('#mDiv').append(' <button class="cBtn">button5</button>')
 }
jQuery(function($){
//使用on代替live和delegate(live由于性能原因已经被废弃,被delegate代替),新添加到mDiv的button依然会有绑定的事件
$('#mDiv').on('click','.cBtn',function(index, eleDom){
alert($(this).html())
 });
//使用on代替bind
$('.cBtn').on('click',function(){
alert($(this).html())
 })
//注意:
/*
1、无论使用bind、on、delegate、click(function())都是重复绑定,即绑定的同类型事件被放到一个事件队列中,依次执行,后绑定的事件不会替换之前绑定的,对于on使用off,delegate用undelegate,bind及click使用unbind来解除绑定,例如unbind(type)传递为事件类型,如果不传type则解出所有事件绑定;需要注意的是元素本身自带的事件无法unbind(如button1)
2、要绑定自定义事件,如'open',以上函数都可以使用,但激活需要使用trigger
总结:
建议使用on函数,绑定形式为$('.myClass').on({
click:function(eleDom){
...do someting...
},
dbclick:function(eleDom){
...do someting...
}
....
})
*/
}
</script>

登入後複製

Some notes:

bind(type,[data],fn) binds an event handler to a specific event for each matched element

Copy code The code is as follows:
$("a").bind("click",function( ){alert("ok");});

live(type,[data],fn) attaches an event handler to all matching elements, even if the element is added later
Copy code The code is as follows:
$("a").live("click",function( ){alert("ok");});

delegate(selector,[type],[data],fn) adds one or more event handlers to the specified element (a child element of the selected element) and specifies the function to run when these events occur
Copy code The code is as follows:
$("#container").delegate("a"," click",function(){alert("ok");})

on(events,[selector],[data],fn) Event handler function that binds one or more events to the selected element

Difference:

.bind() is directly bound to the element

.live() is bound to the element through bubbling. More suitable for list types, bound to document DOM nodes. The advantage of .bind() is that it supports dynamic data.

.delegate() is a more accurate event proxy for small-scale use, and its performance is better than .live()

.on() is the latest version 1.9 that integrates the previous three methods of new event binding mechanism

Additional: The difference between bind and live

There are three ways to bind events in jQuery: take the click event as an example

(1)target.click(function(){});

(2)target.bind("click",function(){});

(3)target.live("click",function(){});

The first method is easy to understand. In fact, it is similar to the usage of ordinary JS, except that one is missing

The second and third methods are all binding events, but they are very different. Let’s focus on explaining them below, because this is used a lot if you use the jQuery framework. Pay special attention to the two the difference between.

【The difference between bind and live】

The live method is actually a variant of the bind method. Its basic function is the same as the bind method. They both bind an event to an element, but the bind method can only bind events to the currently existing element. It is invalid for newly generated elements using JS and other methods afterwards. The live method just makes up for this flaw of the bind method. It can also bind corresponding events to the elements generated later. So how is this feature of the live method implemented? Let’s discuss its implementation principle below.

The reason why the live method can also bind corresponding events to later-generated elements is attributed to "event delegation". The so-called "event delegation" means that events bound to ancestor elements can be bound to descendant elements. for use. The processing mechanism of the live method is to bind the event to the root node of the DOM tree instead of directly binding it to an element. Give an example to illustrate:

$(".clickMe").live("click",fn);
$("body").append("<div class='clickMe'>测试live方法的步骤</div>");

登入後複製

When we click on this new element, the following steps will occur:

(1) Generate a click event and pass it to the div for processing

(2) Since no event is directly bound to the div, the event bubbles up directly to the DOM tree

(3) Events continue to bubble up to the root node of the DOM tree. By default, the click event is bound to the root node

(4) Execute the click event bound by live

(5) Detect whether the object bound to the event exists, and determine whether it is necessary to continue executing the bound event. Detecting event objects is done by detecting

Copy code The code is as follows:
$(event.target).closest('.clickMe')
能否找到匹配的元素來實現的。

(6)通過(5)的測試,如果綁定事件的物件存在的話,就執行綁定的事件。

由於只有在事件發生的時候,live方法才會去偵測綁定事件的物件是否存在,所以live方法可以實作後來新增的元素也可實現事件的綁定。相較之下,bind會在事件在綁定階段就會判斷綁定事件的元素是否存在,而且只針對當前元素進行綁定,而不是綁定到父節點。

根據上面的分析,live的好處真是很大,那為什麼還要使用bind方法呢?之所以jQuery要保留bind方法而不是採用live方法去取代bind,也是因為live在某些情況下是無法完全取代bind的。主要的不同如下:

(1)bind方法可以綁定任何JavaScript的事件,而live方法在jQuery1.3的時候只支援click, dblclick, keydown, keypress, keyup,mousedown, mousemove, mouseout, mouseover, 和mouseup.在jQuery 1.4.1中,甚至也支援focus 和blue事件了(映射到更合適,並且可以冒泡的focusin和focusout上)。另外,在jQuery 1.4.1中,也能支援hover(映射到"mouseenter mouseleave")。

(2)live() 並不完全支援透過DOM遍歷的方法找到的元素。取而代之的是,應當總是在一個選擇器後面直接使用 .live()方法。

(3)當一個元素採用live方法進行事件的綁定的時候,如果想阻止事件的傳遞或冒泡,就要在函數中return false,僅僅調用stopPropagation()是無法實現阻止事件的傳遞或冒泡的

更多關於jQuery事件與方法相關內容有興趣的讀者可查看本站專題:《jQuery常見事件用法與技巧總結

希望本文所述對大家jQuery程式設計有所幫助。

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

BTCC教學:如何在BTCC交易所綁定使用MetaMask錢包? BTCC教學:如何在BTCC交易所綁定使用MetaMask錢包? Apr 26, 2024 am 09:40 AM

MetaMask(中文也叫小狐狸錢包)是一款免費的、廣受好評的加密錢包軟體。目前,BTCC已支援綁定MetaMask錢包,綁定後可使用MetaMask錢包進行快速登錄,儲值、買幣等,且首次綁定還可獲得20USDT體驗金。在BTCCMetaMask錢包教學中,我們將詳細介紹如何註冊和使用MetaMask,以及如何在BTCC綁定並使用小狐狸錢包。 MetaMask錢包是什麼? MetaMask小狐狸錢包擁有超過3,000萬用戶,是當今最受歡迎的加密貨幣錢包之一。它可免費使用,可作為擴充功能安裝在網絡

小紅書怎麼綁定子帳號?它怎麼檢測帳號是否正常? 小紅書怎麼綁定子帳號?它怎麼檢測帳號是否正常? Mar 21, 2024 pm 10:11 PM

在現今這個資訊爆炸的時代,個人品牌和企業形象的建立變得越來越重要。小紅書作為國內領先的時尚生活分享平台,吸引了大量用戶關注和參與。對於那些希望擴大影響力、提高內容傳播效率的使用者來說,綁定子帳號成為了一種有效的手段。那麼,小紅書怎麼綁定子帳號呢?又如何檢測帳號是否正常呢?本文將為您詳細解答這些問題。一、小紅書怎麼綁定子帳號? 1.登入主帳號:首先,您需要登入您的小紅書主帳號。 2.開啟設定選單:點選右上角的“我”,然後選擇“設定”。 3.進入帳號管理:在設定選單中,找到「帳號管理」或「帳號助理」選項,點

今日頭條綁定抖音的步驟方法 今日頭條綁定抖音的步驟方法 Mar 22, 2024 pm 05:56 PM

1、打開今日頭條。 2、點選右下角我的。 3.點選【系統設定】。 4.點選【帳號和隱私設定】。 5.點選【抖音】右邊的按鈕即可綁定抖音。

菜鳥app怎麼綁定拼多多 菜鳥裹裹怎麼添加拼多多平台 菜鳥app怎麼綁定拼多多 菜鳥裹裹怎麼添加拼多多平台 Mar 19, 2024 pm 02:30 PM

菜鳥app就是能夠提供你們各種物流資訊狀況的平台,這裡的功能非常的強大好用,大家有任何與物流相關的問題,都能在這得到解決的,反正都能為你們帶來一站式的服務,全都能及時解決的,查快遞,取快遞,寄快遞等,都是毫無任何問題,與各個的平台都進行了合作,全部的信息,都能查詢得到的,但是有些時候會出現拼多多當中購買的商品,都是無法呈現出物流的信息,其實是需要大家進行手動綁定拼多多,才能實現的,具體的方法已經整理出來了在下方,大家都能來看看的。菜鳥綁定拼多多帳戶的方法:  1、打開菜鳥APP,在主頁面

jQuery中如何使用PUT請求方式? jQuery中如何使用PUT請求方式? Feb 28, 2024 pm 03:12 PM

jQuery中如何使用PUT請求方式?在jQuery中,發送PUT請求的方法與發送其他類型的請求類似,但需要注意一些細節和參數設定。 PUT請求通常用於更新資源,例如更新資料庫中的資料或更新伺服器上的檔案。以下是在jQuery中使用PUT請求方式的具體程式碼範例。首先,確保引入了jQuery庫文件,然後可以透過以下方式發送PUT請求:$.ajax({u

菜鳥APP怎麼綁定拼多多 菜鳥APP綁定拼多多方法 菜鳥APP怎麼綁定拼多多 菜鳥APP綁定拼多多方法 Mar 19, 2024 pm 05:16 PM

你們知道在使用菜鳥裹裹的時候是怎麼來綁定拼多多的嗎?菜鳥裹裹App官方正版在這款平台上面對於一些拼多多的物流信息是沒有自動同步上去的,我們需要做的就只能複製單號過來或是查詢你們的手機看看有無快遞的資訊。當然這些都是需要手動完成的,如果你們也想了解更多的話,就和小編一起來看看吧。  菜鳥APP怎麼綁定拼多多  1、打開菜鳥APP,在主頁點選左上角的「導包裹」。  2、在介面中,有許多購物網站,帳號都可以綁定。  3、點選導入其他電商平台。  4、使用者授權:點選拼多多到介面

小米汽車app怎麼綁定充電樁設備 小米汽車app怎麼綁定充電樁設備 Apr 01, 2024 pm 06:52 PM

最新小米最新推出的小米su7型號汽車霸佔了各種熱搜榜,許多正好有購車需求的用戶們都紛紛選擇了小米su7型號的汽車進行購買,那麼在提車以後如何利用自己的小米汽車app綁定家用充電樁充電呢,那麼這篇教學攻略就會為大家帶來詳細的內容介紹,希望能幫助大家。首先我們先打開小米手機app,點擊右下角我的按鈕然後在我的介面,可以看到家充樁的選項進入到綁定充電樁的頁面以後,點擊下方的去掃碼按鈕,掃描充電樁上的二維碼即可完成充電樁與app的綁定

jQuery小技巧:快速修改頁面所有a標籤的文本 jQuery小技巧:快速修改頁面所有a標籤的文本 Feb 28, 2024 pm 09:06 PM

標題:jQuery小技巧:快速修改頁面所有a標籤的文字在網頁開發中,我們經常需要對頁面中的元素進行修改和操作。使用jQuery時,有時候需要一次修改頁面中所有a標籤的文字內容,這樣可以節省時間和精力。以下將介紹如何使用jQuery快速修改頁面所有a標籤的文本,同時給出具體的程式碼範例。首先,我們需要引入jQuery庫文件,確保在頁面中引入了以下程式碼:&lt

See all articles