1. Event delegation
What is event delegation? A realistic understanding is: 100 students receive express delivery at noon on a certain day at the same time, but it is impossible for these 100 students to stand at the school gate waiting at the same time, so they will entrust the doorman to collect it, and then hand it over to the students one by one. .
In jQuery, we use the event bubbling feature to allow events bound to child elements to bubble up to the parent element (or ancestor element)
, and then perform related processing.
If an enterprise-level application does report processing, the table has 2000 rows, and each row has a button for processing. If you use
previous .bind() processing, then you need to bind 2000 events, just like 2000 students standing at the school gate waiting for
express delivery, which will constantly block the intersection and cause various accidents. The same situation applies to the page, which may cause the page
to be extremely slow or directly abnormal. Moreover, if 2000 buttons are paginated using ajax, the .bind() method cannot dynamically bind elements that
do not exist yet. For example, if the courier cannot verify the identity of a newly transferred student, he may not receive the courier.
//HTML part
<div style="background:red;width:200px;height:200px;" id="box"> <input type="button" value="按钮" class="button" /> </div>//Using .bind() does not have the dynamic binding function, only clicking the original button can generate
$('.button').bind('click', function () { $(this).clone().appendTo('#box'); });//Use .live() has a dynamic binding function, used by jQuery1.3, abandoned after jQuery1.7, and deleted by jQuery1.9
$('.button').live('click', function () { $(this).clone().appendTo('#box'); });.live() principle is to bind the click event to the ancestor element$ (document), you only need to bind
to $(document) once, instead of 2000 times. Then you can handle the click event of the subsequent dynamically loaded button. When accepting any
event, the $(document) object will check the event type (event.type) and event target (event.target). If the click
event is .button, then the processing delegated to it will be performed. program. The .live() method has been deleted and cannot be used. If you need
to test and use it, you need to introduce a backward compatible plug-in.
//.live()无法使用链接连缀调用,因为参数的特性导致 $('#box').children(0).live('click', function () { $(this).clone().appendTo('#box'); });In the above example, we used .clone() to clone. In fact, if we want to copy the event behavior, we only need to pass true: .clone(true). This can also achieve functions similar to event delegation, but the principles are completely different.
One is copy event behavior, and the other is event delegation. Under non-cloning operations, such functions can only use event delegation.
$('.button').live('click', function () { $('<input type="button" value="复制的" class="button" />').appendTo('#box'); });
When we need to stop event delegation, we can use .die() to cancel it.
$('.button').die('click'); 由于.live()和.die()在jQuery1.4.3 版本中废弃了,之后推出语义清晰、减少冒泡传播层次、 又支持链接连缀调用方式的方法:.delegate()和.undelegate()。但这个方法在jQuery1.7 版本中 被.on()方法整合替代了。 $('#box').delegate('.button', 'click', function () { $(this).clone().appendTo('#box'); }); $('#box').undelegate('.button','click'); //支持连缀调用方式 $('div').first().delegate('.button', 'click', function () { $(this).clone().appendTo('div:first'); });
Note: .delegate() needs to specify the parent element, then the first parameter is the current element, the second parameter is the event method, and the third parameter is the execution function. Like the .bind() method, additional parameters can be passed. The .undelegate() and .unbind() methods can directly delete all events, such as: .undelegate('click'). You can also delete namespace events,
For example: .undelegate('click.abc').
Note: .live(), .delegate() and .bind() methods are both event bindings, so the difference is obvious. In terms of usage,
follows two rules: 1. Many elements in the DOM When binding the same event; 2. When there is no upcoming
element binding event in the DOM; we recommend using the event delegate binding method, otherwise we recommend using the ordinary binding of .bind().
two. on, off and one
For this reason, jQuery 1.7 and later introduced the .on() and .off() methods to completely abandon the first three groups.
/
/替代.bind()方式 $('.button').on('click', function () { alert('替代.bind()'); }); //替代.bind()方式,并使用额外数据和事件对象 $('.button').on('click', {user : 'Lee'}, function (e) { alert('替代.bind()' + e.data.user); }); //替代.bind()方式,并绑定多个事件 $('.button').on('mouseover mouseout', function () { alert('替代.bind()移入移出!'); }); //替代.bind()方式,以对象模式绑定多个事件 $('.button').on({ mouseover : function () { alert('替代.bind()移入!'); }, mouseout : function () { alert('替代.bind()移出!'); } }); //替代.bind()方式,阻止默认行为并取消冒泡 $('form').on('submit', function () { return false; });
or
$('form').on('submit', false); //替代.bind()方式,阻止默认行为 $('form').on('submit', function (e) { e.preventDefault(); }); //替代.bind()方式,取消冒泡 $('form').on('submit', function (e) { e.stopPropagation(); }); //替代.unbind()方式,移除事件 $('.button').off('click'); $('.button').off('click', fn); $('.button').off('click.abc'); //替代.live()和.delegate(),事件委托 $('#box').on('click', '.button', function () { $(this).clone().appendTo('#box'); }); //替代.die()和.undelegate(),取消事件委托 $('#box').off('click', '.button'); 注意:和之前方式一样,事件委托和取消事件委托也有各种搭配方式,比如额外数据、 命名空间等等,这里不在赘述。 不管是.bind()还是.on(),绑定事件后都不是自动移除事件的,需要通过.unbind()和.off() 来手工移除。jQuery 提供了.one()方法,绑定元素执行完毕后自动移除事件,可以方法仅触 发一次的事件。 //类似于.bind()只触发一次 $('.button').one('click', function () { alert('one 仅触发一次!'); }); //类似于.delegate()只触发一次 $('#box).one('click', 'click', function () { alert('one 仅触发一次!'); });
<div> <input id="a" type="button" value="按钮1"> <input id="a" type="button" value="按钮2"> </div>jQuery code:
$('div').click(function(e){ alert('事件类型:'+ e.type + ',Value:' + $(e.target).val()); })Click [Button 1], pop-up: Event type: click, Value: Button 1. Note: e.type returns the event type of the object, such as click, mousedown; e.target returns the jQuery object that triggered the event. 4. Recommend a javascript online testing tool that supports JQuery library selection and can test html, css, and js codehttp://jsfiddle.net
The above is the content of javascript event delegation and jQuery event binding on, off and one. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

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.


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

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Linux new version
SublimeText3 Linux latest version

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.
