搜尋
首頁web前端js教程jQuery事件綁定用法詳解(附bind和live的區別)_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
JavaScript的角色:使網絡交互和動態JavaScript的角色:使網絡交互和動態Apr 24, 2025 am 12:12 AM

JavaScript是現代網站的核心,因為它增強了網頁的交互性和動態性。 1)它允許在不刷新頁面的情況下改變內容,2)通過DOMAPI操作網頁,3)支持複雜的交互效果如動畫和拖放,4)優化性能和最佳實踐提高用戶體驗。

C和JavaScript:連接解釋C和JavaScript:連接解釋Apr 23, 2025 am 12:07 AM

C 和JavaScript通過WebAssembly實現互操作性。 1)C 代碼編譯成WebAssembly模塊,引入到JavaScript環境中,增強計算能力。 2)在遊戲開發中,C 處理物理引擎和圖形渲染,JavaScript負責遊戲邏輯和用戶界面。

從網站到應用程序:JavaScript的不同應用從網站到應用程序:JavaScript的不同應用Apr 22, 2025 am 12:02 AM

JavaScript在網站、移動應用、桌面應用和服務器端編程中均有廣泛應用。 1)在網站開發中,JavaScript與HTML、CSS一起操作DOM,實現動態效果,並支持如jQuery、React等框架。 2)通過ReactNative和Ionic,JavaScript用於開發跨平台移動應用。 3)Electron框架使JavaScript能構建桌面應用。 4)Node.js讓JavaScript在服務器端運行,支持高並發請求。

Python vs. JavaScript:比較用例和應用程序Python vs. JavaScript:比較用例和應用程序Apr 21, 2025 am 12:01 AM

Python更適合數據科學和自動化,JavaScript更適合前端和全棧開發。 1.Python在數據科學和機器學習中表現出色,使用NumPy、Pandas等庫進行數據處理和建模。 2.Python在自動化和腳本編寫方面簡潔高效。 3.JavaScript在前端開發中不可或缺,用於構建動態網頁和單頁面應用。 4.JavaScript通過Node.js在後端開發中發揮作用,支持全棧開發。

C/C在JavaScript口譯員和編譯器中的作用C/C在JavaScript口譯員和編譯器中的作用Apr 20, 2025 am 12:01 AM

C和C 在JavaScript引擎中扮演了至关重要的角色,主要用于实现解释器和JIT编译器。1)C 用于解析JavaScript源码并生成抽象语法树。2)C 负责生成和执行字节码。3)C 实现JIT编译器,在运行时优化和编译热点代码,显著提高JavaScript的执行效率。

JavaScript在行動中:現實世界中的示例和項目JavaScript在行動中:現實世界中的示例和項目Apr 19, 2025 am 12:13 AM

JavaScript在現實世界中的應用包括前端和後端開發。 1)通過構建TODO列表應用展示前端應用,涉及DOM操作和事件處理。 2)通過Node.js和Express構建RESTfulAPI展示後端應用。

JavaScript和Web:核心功能和用例JavaScript和Web:核心功能和用例Apr 18, 2025 am 12:19 AM

JavaScript在Web開發中的主要用途包括客戶端交互、表單驗證和異步通信。 1)通過DOM操作實現動態內容更新和用戶交互;2)在用戶提交數據前進行客戶端驗證,提高用戶體驗;3)通過AJAX技術實現與服務器的無刷新通信。

了解JavaScript引擎:實施詳細信息了解JavaScript引擎:實施詳細信息Apr 17, 2025 am 12:05 AM

理解JavaScript引擎內部工作原理對開發者重要,因為它能幫助編寫更高效的代碼並理解性能瓶頸和優化策略。 1)引擎的工作流程包括解析、編譯和執行三個階段;2)執行過程中,引擎會進行動態優化,如內聯緩存和隱藏類;3)最佳實踐包括避免全局變量、優化循環、使用const和let,以及避免過度使用閉包。

See all articles

熱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

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

熱工具

MantisBT

MantisBT

Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。

EditPlus 中文破解版

EditPlus 中文破解版

體積小,語法高亮,不支援程式碼提示功能

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

強大的PHP整合開發環境

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser是一個安全的瀏覽器環境,安全地進行線上考試。該軟體將任何電腦變成一個安全的工作站。它控制對任何實用工具的訪問,並防止學生使用未經授權的資源。

SublimeText3 Mac版

SublimeText3 Mac版

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