亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

Table of Contents
Code analysis
Advantages of event delegation
Things to note
Summarize
Home Web Front-end JS Tutorial Best practices for JavaScript event handling in dynamically generated HTML elements

Best practices for JavaScript event handling in dynamically generated HTML elements

Oct 12, 2025 am 09:24 AM

Best practices for JavaScript event handling in dynamically generated HTML elements

This article explores optimized methods for adding JavaScript event handling on dynamically generated HTML elements. In response to the inefficiency problem of directly embedding <script> tags in each dynamic element, the article details how to use event delegation (Event Delegation) technology to efficiently and elegantly manage events of all dynamic sub-elements by binding a single event listener on the static parent element, thereby improving page performance, simplifying the code structure, and ensuring the reliability of event processing.<h3> Dynamic HTML elements and event handling challenges<p> In modern web applications, we often need to dynamically generate HTML content based on back-end data. For example, get a list of products from the database and render it on the page. When these dynamically generated elements require interactive functions (such as clicking a button to submit a form), how to bind JavaScript events to them becomes a key issue.<p> A common and intuitive approach is to embed a <script> tag to bind events to the newly created elements every time you generate dynamic HTML. Here is a sample code snippet demonstrating this approach:<pre class="brush:php;toolbar:false"> function getWidgets(){ var listUrl = base_url widgetsPath url_auth; console.log(&quot;Sending GET to &quot; listUrl); function getSuccess(obj){ var dataWidget = obj.data; for (let i=0; i&lt; dataWidget.length; i ){ var id = dataWidget[i].id; var description = dataWidget[i].description; var price = dataWidget[i].pence_price; var url = dataWidget[i].url; var index = i; var template =`&lt;!-- product --&gt; &lt;div class=&quot;container&quot; class=&quot;product&quot; id=&quot;productId_${index}&quot;&gt; &lt;form action=&quot;&quot; class=&quot;product&quot;&gt; &lt;img src=&quot;/static/imghw/default1.png&quot; data-src=&quot;${url}&quot; class=&quot;lazy&quot; alt=&quot;Best practices for JavaScript event handling in dynamically generated HTML elements&quot; &gt; &lt;p class=&quot;product_Description&quot;&gt;${description} &lt;input type=&quot;hidden&quot; class=&quot;productId&quot; value=${id}&gt; &lt;input type=&quot;hidden&quot; class=&quot;price&quot; value=&quot;0.${price}&quot;&gt; &lt;label for=&quot;quantity&quot;&gt;Quantity: &lt;input type=&quot;number&quot; class=&quot;quantity&quot; value=&quot;1&quot; min=&quot;1&quot;&gt; &lt;button class=&quot;submit&quot;&gt;Add to cart &lt;script&gt; // Bind events for each dynamically generated form document.addEventListener(&quot;DOMContentLoaded&quot;,() =&gt;{ const productContainer = document.querySelector(&quot;#productId_${index}&quot;) productContainer.querySelector(&quot;form.product&quot;).addEventListener(&quot;submit&quot;,e=&gt;{ e.preventDefault(); var formId = &quot;productId_${index}&quot;; productList(formId); }); }); &lt;/script&gt; &lt;!-- END product --&gt;` $(&quot;#widgetContainer&quot;).append(template); } console.log(&quot;success&quot;); console.log(dataWidget); }; $.ajax(listUrl, {type: &quot;GET&quot;, data: {},success: getSuccess }); }; getWidgets();&lt;p&gt; Although this method can achieve the function, it has obvious disadvantages:&lt;/p&gt; &lt;ol&gt; &lt;li&gt; &lt;strong&gt;High performance overhead:&lt;/strong&gt; Each time a dynamic element is generated, a &lt;script&gt; tag is inserted and executed. If the number of dynamic elements is large, it will cause a large number of DOM operations and script parsing, seriously affecting page performance.&lt;/script&gt; &lt;/li&gt; &lt;li&gt; &lt;strong&gt;Code redundancy:&lt;/strong&gt; A large amount of repeated event binding logic is scattered in HTML templates, making it difficult to maintain.&lt;/li&gt; &lt;li&gt; &lt;strong&gt;Memory usage:&lt;/strong&gt; Creating a separate event listener for each dynamic element will take up more memory resources.&lt;/li&gt; &lt;li&gt; &lt;strong&gt;Timing issues:&lt;/strong&gt; The DOMContentLoaded event may be triggered after dynamic content is inserted, resulting in event binding failure or delay.&lt;/li&gt; &lt;/ol&gt; &lt;h3&gt; Solution: Event Delegation&lt;/h3&gt; &lt;p&gt; In order to handle events on dynamically generated elements efficiently and elegantly, the best practice is to use &lt;strong&gt;event delegation (Event Delegation)&lt;/strong&gt; . The core idea of ??event delegation is: not to directly bind an event listener to each dynamic child element, but to bind a listener to their common, &lt;strong&gt;statically existing parent element&lt;/strong&gt; . When an event on a child element is triggered, the event will bubble up to the parent element along the DOM tree. After the listener on the parent element captures the event, it will determine which child element triggered the event based on the event source (event.target), and execute the corresponding processing logic.&lt;/p&gt; &lt;h4&gt; How to implement event delegation&lt;/h4&gt; &lt;p&gt; Using jQuery, event delegation can be easily implemented through the on() method. The syntax is: $(staticParentSelector).on(eventName, dynamicChildSelector, handlerFunction).&lt;/p&gt; &lt;p&gt; Here is a code example that uses event delegation to refactor the above problem:&lt;/p&gt; &lt;p&gt; First, we need to modify the dynamic HTML generation logic and &lt;strong&gt;remove the inline &lt;script&gt; tag&lt;/script&gt;&lt;/strong&gt; :&lt;/p&gt; &lt;pre class=&quot;brush:php;toolbar:false&quot;&gt; function getWidgets(){ var listUrl = base_url widgetsPath url_auth; console.log(&quot;Sending GET to &quot; listUrl); function getSuccess(obj){ var dataWidget = obj.data; for (let i=0; i &lt;div class=&quot;container&quot; id=&quot;productId_${index}&quot;&gt; &lt;form action=&quot;&quot; class=&quot;product&quot;&gt; &lt;img src=&quot;/static/imghw/default1.png&quot; data-src=&quot;${url}&quot; class=&quot;lazy&quot; alt=&quot;Best practices for JavaScript event handling in dynamically generated HTML elements&quot; &gt; &lt;p class=&quot;product_Description&quot;&gt;${description}&lt;/p&gt; &lt;input type=&quot;hidden&quot; class=&quot;productId&quot; value=&quot;${id}&quot;&gt; &lt;input type=&quot;hidden&quot; class=&quot;price&quot; value=&quot;0.${price}&quot;&gt; &lt;label for=&quot;quantity&quot;&gt;Quantity:&lt;/label&gt; &lt;input type=&quot;number&quot; class=&quot;quantity&quot; value=&quot;1&quot; min=&quot;1&quot;&gt; &lt;button class=&quot;submit&quot;&gt;Add to cart&lt;/button&gt; &lt;/form&gt; &lt;/div&gt; &lt;!-- END product --&gt;` // Note: The &lt;script&gt; tag has been removed here $(&quot;#widgetContainer&quot;).append(template); } console.log(&quot;success&quot;); console.log(dataWidget); }; $.ajax(listUrl, {type: &quot;GET&quot;, data: {},success: getSuccess }); }; getWidgets();&lt;/script&gt;</pre> <p> Then, after the page is loaded (or after the getWidgets() function is called, ensuring that #widgetContainer already exists), add a <strong>global event delegate listener</strong> :</p> <pre class="brush:php;toolbar:false"> //Set the event delegate after the page is loaded $(document).ready(function() { // Assume #widgetContainer is the static parent element of all dynamic product containers // Listen to the submit event of all forms with class &quot;product&quot; inside #widgetContainer $('#widgetContainer').on('submit', 'form.product', function (e) { e.preventDefault(); // Prevent form default submission behavior (page refresh) // $(this) here points to the </pre> <form class="product"> element that actually triggered the event // Get the id of its parent div.container const formId = $(this).parent().attr('id'); //Call the business logic function productList(formId); }); });<h4 id="Code-analysis"> Code analysis</h4> <ul><li> $('#widgetContainer'): This is the static parent element to which the event listener is bound. #widgetContainer must be an element that already exists on the page and will not be dynamically removed. It is the ancestor element of all dynamically generated <div class="container" ...>.<li> .on('submit', 'form.product', function (e) { ... }): This is jQuery's event delegation syntax.<ul> <li> 'submit': Specifies the event type to listen for.</li> <li> 'form.product': This is <strong>the selector</strong> , which tells jQuery that only when the event source (e.target) matches this selector, the subsequent processing function will be executed. This means that even if the event bubbles up to the #widgetContainer, the handler will only execute if it was originally triggered from a <form> element (and that element has the product class).</form> </li> <li> function (e) { ... }: This is the event handling function.<ul> <li> e.preventDefault();: Prevent the default submission behavior of the form, that is, prevent the page from refreshing.</li> <li> $(this): In the event handler function, the this keyword points to <strong>the element matching the selector 'form.product' that</strong> actually triggered the event, rather than the #widgetContainer to which the listener is bound.</li> <li> $(this).parent().attr('id');: Get the <form> element that triggered the submit event through $(this), then find its direct parent element (in this case, <div class="container" ...>) through .parent(), and finally get the id attribute of the parent element.<li> productList(formId);: Call the predefined business logic function and pass in the obtained form ID.</li> <h3 id="Advantages-of-event-delegation"> Advantages of event delegation</h3> <ol> <li> <strong>Performance optimization:</strong> Only one event listener needs to be bound to the static parent element instead of multiple listeners for each dynamic child element, which greatly reduces DOM operations and memory usage.</li> <li> <strong>Automatic adaptation:</strong> Any time a new element is added to #widgetContainer and conforms to the form.product selector, it will automatically have the same event handling capabilities without additional code.</li> <li> <strong>Simple code:</strong> Event binding logic is centrally managed, making the code clearer and easier to maintain.</li> <li> <strong>Avoid timing issues:</strong> As long as the parent element exists when the page loads, the event listener can be bound immediately, without having to worry about when the dynamic element is created.</li> </ol> <h3 id="Things-to-note"> Things to note</h3> <ul> <li> <strong>Choose an appropriate static parent element:</strong> The parent element must exist when the page loads and be the common ancestor of all dynamic child elements. The closer the static parent element is to the dynamic child element, the shorter the path for event bubbling and the higher the efficiency.</li> <li> <strong>Make sure the selector is accurate:</strong> The second parameter (dynamicChildSelector) in the on() method must accurately match the dynamic child element you want to handle the event.</li> <li> <strong>Understand this context:</strong> In the handler function of the event delegate, this points to the element that triggered the event and matched the dynamicChildSelector, not the parent element to which the listener is bound.</li> <li> <strong>Event bubbling:</strong> Event delegation relies on the event bubbling mechanism. If an event is prevented from bubbling by a child element (e.g. using e.stopPropagation()), the parent element may not catch the event.</li> </ul> <h3 id="Summarize"> Summarize</h3> <p> When handling events for dynamically generated HTML elements, event delegation is a superior solution than directly embedding <script> tags or binding events individually to each element. It significantly improves performance, simplifies code structure, and ensures reliable and scalable event handling by centrally managing events on static parent elements. Mastering event delegation is one of the key skills for writing efficient, maintainable JavaScript code.</script>

The above is the detailed content of Best practices for JavaScript event handling in dynamically generated HTML elements. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

ArtGPT

ArtGPT

AI image generator for creative art from text prompts.

Stock Market GPT

Stock Market GPT

AI powered investment research for smarter decisions

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

JavaScript realizes click-through image switching effect: professional tutorial JavaScript realizes click-through image switching effect: professional tutorial Sep 18, 2025 pm 01:03 PM

This article will introduce how to use JavaScript to achieve the effect of clicking on images. The core idea is to use HTML5's data-* attribute to store the alternate image path, and listen to click events through JavaScript, dynamically switch the src attributes, thereby realizing image switching. This article will provide detailed code examples and explanations to help you understand and master this commonly used interactive effect.

How to get the user's location with the Geolocation API in JavaScript? How to get the user's location with the Geolocation API in JavaScript? Sep 21, 2025 am 06:19 AM

First, check whether the browser supports GeolocationAPI. If supported, call getCurrentPosition() to get the user's current location coordinates, and obtain the latitude and longitude values ??through successful callbacks. At the same time, provide error callback handling exceptions such as denial permission, unavailability of location or timeout. You can also pass in configuration options to enable high precision, set the timeout time and cache validity period. The entire process requires user authorization and corresponding error handling.

The Nuxt 3 Composition API Explained The Nuxt 3 Composition API Explained Sep 20, 2025 am 03:00 AM

Nuxt3's Composition API core usage includes: 1. definePageMeta is used to define page meta information, such as title, layout and middleware, which need to be called directly in it and cannot be placed in conditional statements; 2. useHead is used to manage page header tags, supports static and responsive updates, and needs to cooperate with definePageMeta to achieve SEO optimization; 3. useAsyncData is used to securely obtain asynchronous data, automatically handle loading and error status, and supports server and client data acquisition control; 4. useFetch is an encapsulation of useAsyncData and $fetch, which automatically infers the request key to avoid duplicate requests

How to create a repeating interval with setInterval in JavaScript How to create a repeating interval with setInterval in JavaScript Sep 21, 2025 am 05:31 AM

To create a repetition interval in JavaScript, you need to use the setInterval() function, which will repeatedly execute functions or code blocks at specified milliseconds intervals. For example, setInterval(()=>{console.log("Execute every 2 seconds");},2000) will output a message every 2 seconds until it is cleared by clearInterval(intervalId). It can be used in actual applications to update clocks, poll servers, etc., but pay attention to the minimum delay limit and the impact of function execution time, and clear the interval in time when no longer needed to avoid memory leakage. Especially before component uninstallation or page closing, ensure that

How to copy text to the clipboard in JavaScript? How to copy text to the clipboard in JavaScript? Sep 18, 2025 am 03:50 AM

Use the writeText method of ClipboardAPI to copy text to the clipboard, it needs to be called in security context and user interaction, supports modern browsers, and the old version can be downgraded with execCommand.

How to create a multi-line string in JavaScript? How to create a multi-line string in JavaScript? Sep 20, 2025 am 06:11 AM

TheBestAtOrreatEamulti-LinestringinjavascriptSisingStisingTemplatalalswithbacktTicks, whichpreserveTicks, WhichpreserveReKeAndEExactlyAswritten.

How to create and use Immediately Invoked Function Expressions (IIFE) in JavaScript How to create and use Immediately Invoked Function Expressions (IIFE) in JavaScript Sep 21, 2025 am 05:04 AM

AnIIFE(ImmediatelyInvokedFunctionExpression)isafunctionthatrunsassoonasitisdefined,createdbywrappingafunctioninparenthesesandimmediatelyinvokingit,whichpreventsglobalnamespacepollutionandenablesprivatescopethroughclosure;itiswrittenas(function(){/cod

How to parse a JSON string into a JavaScript object How to parse a JSON string into a JavaScript object Sep 21, 2025 am 05:43 AM

To parse JSON strings into JavaScript objects, you should use the JSON.parse() method, which can convert valid JSON strings into corresponding JavaScript objects, supports parsing nested objects and arrays, but will throw an error for invalid JSON. Therefore, you need to use try...catch to handle exceptions. At the same time, you can convert the value during parsing through the reviver function of the second parameter, such as converting the date string into a Date object, thereby achieving safe and reliable data conversion.

See all articles