Home > Web Front-end > JS Tutorial > jquery new element event binding problem solution_jquery

jquery new element event binding problem solution_jquery

WBOY
Release: 2016-05-16 16:44:44
Original
1210 people have browsed it

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.

Copy code The code is as follows:






;/button>


This line originally had Delete



Usually, I would bind like this


Copy code The code is as follows: jQuery(function($){
//Already There is a delete button initialized to bind the delete event
$(".del").click(function() {
$(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.
How to solve this problem? 4 solutions are provided below:


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!



Copy code The code is as follows:Delete
jQuery(function($){
//Add row
$("#add2").click(function( ){
$("#table2>tbody").append('New row

is to bind event handlers to existing elements when domready is in place, and then bind them again when newly added elements are added.



jQuery(function($){
//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.



Copy code The code is as follows:

Delete

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('Add new row')
});
});


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
Copy the code The code is as follows:

.template{display:none;}


Here is the template



This line originally had



This line originally had



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.
Copy code The code is as follows:




Here is the template
< td>


This line originally had

< /tr>

This line originally had








< /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
Copy the code The code is as follows:



  • Here is the template



  • This line originally had



  • This line originally had
    Delete




  • Related labels:
    source:php.cn
    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
    Popular Tutorials
    More>
    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template