Home > Web Front-end > JS Tutorial > Detailed explanation of jQuery event binding usage (with the difference between bind and live)_jquery

Detailed explanation of jQuery event binding usage (with the difference between bind and live)_jquery

WBOY
Release: 2016-05-16 15:19:21
Original
1394 people have browsed it

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>

Copy after login

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>

Copy after login

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

Copy after login

When we click on this newly added 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, this 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 the bound event needs to continue to be executed. Detecting event objects is done by detecting

Copy code The code is as follows:
$(event.target).closest('.clickMe')
Can it be achieved by finding matching elements.

(6) Through the test of (5), if the object bound to the event exists, the bound event will be executed.

Since the live method will detect whether the object bound to the event exists only when an event occurs, the live method can implement later added elements and event binding. In contrast, bind will determine whether the element to which the event is bound exists during the binding phase of the event, and will only bind to the current element, not to the parent node.

According to the above analysis, the benefits of live are really great, so why should we use the bind method? The reason why jQuery retains the bind method instead of using the live method to replace bind is because live cannot completely replace bind in some cases. The main differences are as follows:

(1) The bind method can bind any JavaScript event, while the live method only supports click, dblclick, keydown, keypress, keyup, mousedown, mousemove, mouseout, mouseover, and mouseup in jQuery 1.3. In jQuery In 1.4.1, focus and blue events are even supported (mapped to focusin and focusout, which are more suitable and can bubble up). In addition, in jQuery 1.4.1, hover (mapped to "mouseenter mouseleave") is also supported.

(2) live() does not fully support elements found through DOM traversal. Instead, you should always use the .live() method directly after a selector.

(3) When an element uses the live method to bind events, if you want to prevent the delivery or bubbling of events, you must return false in the function. Simply calling stopPropagation() cannot prevent the delivery of events. Or bubbling

Readers who are interested in more content related to jQuery events and methods can check out this site's special topic: "Summary of jQuery common event usage and techniques"

I hope this article will be helpful to everyone in jQuery programming.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template