jquery new element event binding problem solution_jquery
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.
< td>
< /tr>
< /tfoot>
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

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

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

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

Hot Topics



There are 4 ways to bind events in jquery, namely: bind(), live(), delegate() and on() methods; the bind() method can only bind events to existing elements, while the live() ), on(), and delegate() all support event binding for newly added elements in the future.

When developing applications using UniApp, you may encounter the following error message: 'xxx' event is not bound. This is caused by UniApp's event binding mechanism, which needs to be set correctly to solve this problem. 1. Cause of the problem In UniApp, event binding of page components is completed through the v-on instruction. For example, add a button component to the template: <button@click="onClick">Click me</butto

As a scripting language, JavaScript can bind events to elements on the page, so that when a specified event occurs, the corresponding event handler can be automatically called to handle the event. So how to add events to elements? The following article will introduce to you three ways to bind events in JS. I hope it will be helpful to you!

The function of jquery binding event: Bind ordinary events to DOM nodes. When the DOM node is selected, bind the event to it to facilitate users to provide corresponding operations. jQuery provides four event binding methods, namely bind, live, delegate, and on, and the corresponding unlistening functions are unbind, die, undelegate, and off.

jQuery is a popular JavaScript library that is widely used to handle interactivity in web pages. Among them, event binding is one of the important functions of jQuery. Through event binding, responses to user interactions can be achieved. This article will explore jQuery event binding technology and give specific code examples. 1. The basic concept of event binding Event binding refers to adding an event listener on a DOM element to perform specified operations when a specific event occurs. In jQuery, select the desired

Vue is a popular JavaScript framework for building modern web applications. In Vue, we usually use directives to operate DOM elements. Among them, the "click" event is one of the commonly used instructions. However, in Vue applications, we often encounter situations where the "click" event binding is invalid. This article explains how to solve this problem. The first step in checking whether an element exists is to confirm whether the element to which you want to bind a "click" event exists. If the element does not exist,

Vue is a popular JavaScript framework that uses data-driven ideas to simplify the development process. Vue's event binding function is very powerful and can handle various interactions on the page. In the development process of Vue, event binding function parameters are often used. This article will introduce the use of this function in detail. In Vue, you can use the v-on directive to bind events. The v-on directive is followed by the event name and event handling function, for example: <bu

jQuery is a popular JavaScript library that simplifies many common tasks in web development, including element selection, DOM manipulation, and event handling. In jQuery, event binding is one of the very common and important operations. This article will explore the event binding methods in jQuery in detail, and use specific code examples to help readers better understand and apply these methods. 1.bind() method The bind() method is one of the most traditional and commonly used event binding methods. it can
