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 core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.


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

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

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.

Zend Studio 13.0.1
Powerful PHP integrated development environment

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

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),
