


Detailed explanation of the steps to dynamically add click events in jquery
This time I will bring you a detailed explanation of the steps for dynamically adding click events to jquery. What are the precautions for jquery to dynamically add click events? Here is a practical case. Let’s take a look. .
When we try to bind some events to DOM elements, we usually use the following four methods bind(),on(),live( ), delegate()
The first two methods should be used more often. The following is my understanding of the four methods:
Bind(): .bind() is the most direct binding method, which will bind the specified function and Events are transferred to the DOM. This method solves the browser compatibility problem in Event processing, but this method still has some problems. Code:
$( "#members li a" ).bind( "click", function( e ) {} ); $( "#members li a" ).click( function( e ) {} );
The above two lines of code accomplish the same task, which is to add the event handler to all matching a elements. There are some efficiency issues here. On the one hand, we add click events to all a tags. This process is expensive; on the other hand, it is also a waste during execution, because they all do The same thing is executed many times (we can hook them to their parent elements, distinguish each of them by bubbling, and then execute the event handle).
Advantages
This method provides a compatibility solution for event handling between various browsers
Very convenient binding events to elements
.click(), .hover()...These very convenient time bindings are all bind A simplified processing method
is very good for elements selected by ID. Not only can it be hooked quickly (the page can only have one ID), but when the event When it occurs, the handler can be executed immediately (equivalent to the later live, delegate) implementation method
Disadvantages
It will bind events to all filtered elements
It will not bind events to those elements that are dynamically added after it completes execution
When there are many filtered elements, efficiency problems may occur.
Bind() can only be performed when the page is loaded, so efficiency problems may occur.
.live()
.live() method uses the concept of event delegation to handle event binding. It is the same as using .bind() to bind events. The .live() method will bind the corresponding event to the root element of the element you selected, which is the document element. Then all events that bubble up can be handled by this same handler. Its processing mechanism is like this. Once the event bubbles to the document, jQuery will look for the selector/event metadata and then decide which handler should be called. However, it seems to have been deleted in the latest jquery version.
$( "#members li a" ).live( "click", function( e ) {} );
Advantages:
#There is only one event binding here, which is bound to the document instead of .bind(). All elements are bound one by one
Those dynamically added elemtns can still trigger events that were bound earlier, because the actual binding of the event is on the document
You can bind the required events before the document is ready
Disadvantages:
- # #It has been deprecated since 1.7, so you have to start phasing it out too.
- Chaining is not supported correctly
- It is useless when using event.stopPropagation() because it has to reach the document
- Because all selectors/events are bound to documents,
so when we use the matchSelector method to select which event is called, it will be very slow
- When the element where the event occurs is very deep in your DOM tree, there will be performance problems
.Delegate()
.delegate()有点像.live(),不同于.live()的地方在于,它不会把所有的event全部绑定到document,而是由你决定把它放在哪儿。而和.live()相同的地方在于都是用event delegation.推荐使用.delegate() 代替.live()
$( "#members" ).delegate( "li a", "click", function( e ) {} );
优点:
你可以选择你把这个事件放到那个元素上了 chaining被正确的支持了
jQuery仍然需要迭代查找所有的selector/eventdata来决定那个子元素来匹配,但是因为你可以决定放在那个根元素上,所以可以有效的减小你所要查找的元素。
可以用在动态添加的元素上
缺点:
需要查找那个那个元素上发生了那个事件了,尽管比document少很多了,不过,你还是得浪费时间来查找。
.On()
其实.bind(), .live(), .delegate()都是通过.on()来实现的,.unbind(), .die(), .undelegate(),也是一样的都是通过.off()来实现的,这是1.8.2的源码:
$( "#members li a" ).on( "click", function( e ) {} ); $( "#members li a" ).bind( "click", function( e ) {} ); // Live $( document ).on( "click", "#members li a", function( e ) {} ); $( "#members li a" ).live( "click", function( e ) {} ); // Delegate $( "#members" ).on( "click", "li a", function( e ) {} ); $( "#members" ).delegate( "li a", "click", function( e ) {} );
优点:
提供了一种统一绑定事件的方法
仍然提供了.delegate()的优点,当然如果需要你也可以直接用.bind()
缺点:
也许会对你产生一些困扰,因为它隐藏了一前面我们所介绍的三种方法的细节。
结论:
用.bind()的代价是非常大的,它会把相同的一个事件处理程序hook到所有匹配的DOM元素上
不要再用.live()了,它已经不再被推荐了,而且还有许多问题
.delegate()会提供很好的方法来提高效率,同时我们可以添加一事件处理方法到动态添加的元素上。
我们可以用.on()来代替上述的3种方法
相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!
推荐阅读:
webkit-font-smoothing字体抗锯齿渲染使用案例详解
The above is the detailed content of Detailed explanation of the steps to dynamically add click events in jquery. For more information, please follow other related articles on the PHP Chinese website!

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 Chinese version
Chinese version, very easy to use

Dreamweaver Mac version
Visual web development tools

Atom editor mac version download
The most popular open source editor

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

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.