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

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

WBOY
WBOY原創
2016-05-16 15:19:211418瀏覽

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