


Detailed explanation of jQuery event binding usage (with the difference between bind and 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
live(type,[data],fn) attaches an event handler to all matching elements, even if the element is added later
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
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 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
(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.

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



MetaMask (also called Little Fox Wallet in Chinese) is a free and well-received encryption wallet software. Currently, BTCC supports binding to the MetaMask wallet. After binding, you can use the MetaMask wallet to quickly log in, store value, buy coins, etc., and you can also get 20 USDT trial bonus for the first time binding. In the BTCCMetaMask wallet tutorial, we will introduce in detail how to register and use MetaMask, and how to bind and use the Little Fox wallet in BTCC. What is MetaMask wallet? With over 30 million users, MetaMask Little Fox Wallet is one of the most popular cryptocurrency wallets today. It is free to use and can be installed on the network as an extension

In today's era of information explosion, the construction of personal brand and corporate image has become increasingly important. As the leading fashion life sharing platform in China, Xiaohongshu has attracted a large number of user attention and participation. For those users who want to expand their influence and improve the efficiency of content dissemination, binding sub-accounts has become an effective means. So, how does Xiaohongshu bind a sub-account? How to check whether the account is normal? This article will answer these questions for you in detail. 1. How to bind a sub-account on Xiaohongshu? 1. Log in to your main account: First, you need to log in to your Xiaohongshu main account. 2. Open the settings menu: click "Me" in the upper right corner, and then select "Settings". 3. Enter account management: In the settings menu, find the "Account Management" or "Account Assistant" option and click

1. Open Toutiao. 2. Click My in the lower right corner. 3. Click [System Settings]. 4. Click [Account and Privacy Settings]. 5. Click the button on the right side of [Douyin] to bind Douyin.

The Cainiao app is a platform that can provide you with various logistics information. The functions here are very powerful and easy to use. If you have any logistics-related problems, they can be solved here. Anyway, it can bring you a The one-stop service can solve everything in time. Checking the express delivery, picking up the express delivery, sending the express delivery, etc. are all without any problems. We have cooperated with various platforms and all the information can be queried. However, sometimes It will happen that the goods purchased on Pinduoduo cannot display the logistics information. In fact, you need to manually bind Pinduoduo to achieve this. The specific methods have been sorted out below, and everyone can take a look. . How to bind Cainiao to Pinduoduo account: 1. Open Cainiao APP and go to the main page

How to use PUT request method in jQuery? In jQuery, the method of sending a PUT request is similar to sending other types of requests, but you need to pay attention to some details and parameter settings. PUT requests are typically used to update resources, such as updating data in a database or updating files on the server. The following is a specific code example using the PUT request method in jQuery. First, make sure you include the jQuery library file, then you can send a PUT request via: $.ajax({u

The latest Mi su7 model car launched by Xiaomi has dominated various hot search lists. Many users who happen to want to buy a car have chosen Xiaomi su7 model car for purchase. So how do you use your Xiaomi car app to bind the car after picking up the car? If you decide to use a home charging pile for charging, this tutorial guide will give you a detailed introduction, I hope it can help you. First, we open the Xiaomi mobile app, click the My button in the lower right corner, and then in the My interface, you can see the option of home charging pile. After entering the page to bind the charging pile, click the scan code button below and scan the QR code on the charging pile. The QR code can be used to bind the charging pile to the app.

Do you know how to bind Pinduoduo when using Cainiao Wrap? The official version of Cainiao Wrap App does not automatically synchronize some Pinduoduo’s logistics information on this platform. All we need to do is You can copy the order number or check your mobile phone to see if there is any express delivery information. Of course, these all need to be completed manually. If you want to know more, come and take a look with the editor. How to bind the Cainiao APP to Pinduoduo 1. Open the Cainiao APP and click "Package Guide" in the upper left corner of the main page. 2. In the interface, there are many shopping websites, and accounts can be bound. 3. Click to import other e-commerce platforms. 4. User authorization: Click Pinduoduo to go to the interface

The inability of the Black Box to bind to Steam may be caused by network or software version issues. The little black box provides information including prices of released and upcoming games, computer configuration requirements and reviews, and in-depth gameplay analysis. In addition, it also allows users to find the information they need through mobile devices anytime and anywhere. What to do if the little black box cannot be bound to Steam 1. Confirm the network status and make sure the device is connected to the Internet. 2. Check the Little Black Box version. Please make sure you are using the latest version of the Little Black Box software and try to bind your Steam account. 3. To check the Steam account settings, please log in to the Steam account and check whether the third-party software binding function is turned on in the privacy settings. 4. Contact official customer service If the above steps still cannot solve the problem, it is recommended that you contact official customer service for help.
