The event monitoring of js is different from that of css. As long as the style of css is set, whether it is existing or newly added, it will have the same performance. But event listening is not the case. You must bind events to each element individually.
A common example is when processing tables. There is a delete button at the end of each line. Click this to delete this line.
This line originally had |
Usually, I would bind like this
$(this).parents("tr").remove();
});
});
Everything works perfectly for the delete button that existed before domready. But if you use js to dynamically add a few lines after domready, the buttons in the newly added lines will lose any effect.
Solution No. 0 - onclick method
If you ignore the principle of separation of structure and behavior, usually, I will do this. Note that the deltr function at this time must be a global function and must be placed outside jQuery(function($) {}). If placed inside, it becomes a local function, and onclick in html cannot be called!
//Add row
$("#add2").click(function( ){
$("#table2>tbody").append('
});
});
//The function to delete rows must be placed outside the domready function
function deltr(delbtn){
$(delbtn).parents("tr").remove();
};
Solution No. 1 - Repeat binding The formula
is to bind event handlers to existing elements when domready is in place, and then bind them again when newly added elements are added.
//Define the delete button event binding
//Write it inside to prevent contamination of the global namespace
function deltr(){
$(this).parents("tr").remove();
};
//There is already a delete button initialized to bind the delete event
$( "#table3 .del").click(deltr);
//Add row
$("#add3").click(function(){
$('
//Delete here The button is bound to the event again.
.find(".del").click(deltr).end()
.appendTo($("#table3>tbody"));
});
});
Solution No. 2 - Event bubbling method
Using the principle of event bubbling, we give the ancestor element of this button Bind event handler function. Then use the event.target object to determine whether this event was triggered by the object we are looking for.
Usually you can use some DOM attributes, such as event.target.className, event.target.tagName, etc. to judge.
jQuery(function($){
//Fourth The delete button event binding of a table
$("#table4").click(function(e) {
if (e.target.className=="del"){
$(e. target).parents("tr").remove();
};
});
//Add button event binding of the fourth table
$("#add4") .click(function(){
$("#table4>tbody").append('
});
});
No. 3 Solution - Copy event method
The above solutions can be said to be relatively easy to implement even if you do not use the jQuery library. But this solution relies more heavily on jQuery. And it must require jQuery version 1.2 or above. Lower versions of jQuery require plug-ins.
Both the above two solutions put a lot of thought into the deletion function and changed a variety of triggering and binding methods. This solution is different. It can be bound at domready time just like the usual purely static elements. But when we add a new line, let's change it. We no longer want to add a new line by splicing strings as above. This time we try to copy DOM elements. And when copying, copy it together with the bound event. After copying, use find or the like to modify the internal elements.
At the same time, just like this example, if you will delete all elements, then the template is necessary. If you will not delete them, then you may not need to use template. In order to prevent accidental deletion, I have hidden the template here.
I used the unique clone(true) in jQuery
.template{display:none;}
jQuery(function($){
//Delete button event binding of the fifth table
$("#table5 .del").click(function() {
$(this) .parents("tr").remove();
});
//Add button event binding of the fifth table
$("#add5").click(function(){
$("#table5>tbody>tr:eq(0)")
//Copy together with the event
.clone(true)
//Remove the template tag
.removeClass( "template")
//Modify internal elements
.find("td:eq(0)")
.text("New row")
.end()
/ /Insert table
.appendTo($("#table5>tbody"))
});
});
Overall comments:
The above 4 options have their own advantages and disadvantages.
Plan No. 0, there is no separation between structure and behavior, and it pollutes the global namespace. Least recommended. So I don’t even think of it as a plan. But for js beginners, it can be used for emergency projects.
Option 1, quite satisfactory, nothing good or bad.
Option 2, this method fully utilizes the advantages of js event bubbling. And the most efficient. But at the same time, because this solution ignores jQuery's powerful selector, it will be more troublesome if there are too many element attribute requirements involved. You will be wandering among the right and wrong relationships of many if conditions. Later I remembered that I could use $(event.target).is(selector) in jQuery as a condition. This can greatly improve development efficiency, but slightly reduce execution efficiency.
Plan No. 3, this is the plan that I think best embodies the idea of separation of structure and behavior. But the shortcomings are also obvious. The dependence on jQuery is too high. Otherwise, you have to write a function that copies the event together, but this is obviously extremely difficult for beginners. But from the perspective of future trends, this solution is still highly recommended.
There is no definite number on which plan to choose. It depends on your project and your mastery of js and the idea of separation of structure and behavior. The most suitable one is the best.
Additional:
Transform Plan 3 into a perfect structure-behavior separation style.
First of all, with template is the template element. It is the source of all copies. In order to prevent accidental deletion, it is set to invisible. This template element is also optional if the light will not be removed. Because you can copy any existing element for looping.
Secondly, add a repeat to each repeated element to facilitate the delete button to find this level of elements. This is optional and sometimes not required.
Finally, add a class to each element to be modified so that it can be found using find. For example, I have a content class here, and the newly added one can modify the value inside.
This completes a perfect case of separation of structure and behavior.
jQuery(function($){
//Delete button event binding of the sixth table
$("#tbody6 .del" ).click(function() {
$(this).parents(".repeat").remove();
});
//Add button event binding for the sixth table
$("#add6").click(function(){
$("#tbody6>.template")
//Copy together with the event
.clone(true)
/ /Remove template tags
.removeClass("template")
//Modify internal elements
.find(".content")
.text("New line")
.end ()
//Insert table
.appendTo($("#tbody6"))
});
});
Similarly, this js also Applicable to the following html structure
Here is the template
This line originally had
This line originally had
Delete

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.

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.


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

Dreamweaver CS6
Visual web development tools

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

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Zend Studio 13.0.1
Powerful PHP integrated development environment

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool