jquery new Element Event binding problem Solution _jquery

Source: Internet
Author: User
Tags event listener jquery library

JS event monitoring and CSS is not the same, CSS as long as set the style, whether the original or new additions, have the same performance. Instead of the event listener, you must bind each element individually to the event.

A common example is when a table is processed. There is a delete button at the end of each line, and this is the ability to delete the line.

Copy Code code as follows:

<table>
<tbody>
<tr>
<td> This line has a </td>
<td><buttonclass= "del" > Delete </button></td>
</tr>
<tr>
<td> This line has a </td>
<td><buttonclass= "del" > Delete </button></td>
</tr>
</tbody>
</table>

Normally, I would be so bound
Copy Code code as follows:

JQuery (function ($) {
Delete button is already initialized binding Delete event
$ (". Del"). Click (function () {
$ (this). Parents ("tr"). Remove ();
});
});

Everything is perfect for the delete button that existed before Domready. But if you add a few lines with JS after Domready, the buttons in the new lines will lose any effect.

How to solve this problem? The following 4 solutions are available:

number No. 0 Solution--onclick Method

I would normally do this without disregarding the principle of separation of structure and behavior.
Note that this function must be a global function, you have to put jquery (function ($) {}) outside, put inside the local function, the deltr in HTML can not call the onclick!
Copy Code code as follows:

<td><buttononclick= "deltr (This)" > Delete </button></td>

JQuery (function ($) {
Add rows
$ ("#add2"). Click (function () {
$ ("#table2 >tbody"). Append (' <tr><td> New line </td><td><button nclick= ' deltr (this) > delete </button></td></tr> ')
});
});
To delete a function of a row, you must put the Domready function outside
function deltr (delbtn) {
$ (DELBTN). Parents ("tr"). Remove ();
};

number 1th Solution--Repeated binding method

That is, to bind an event handler function to an existing element when Domready.
And then bind again when the new element is added.
Copy Code code as follows:

<td><buttonclass= "del" > Delete </button></td>

JQuery (function ($) {
Define Delete button Event bindings
Write inside to prevent pollution global namespaces
function deltr () {
$ (this). Parents ("tr"). Remove ();
};
Delete button is already initialized binding Delete event
$ ("#table3. Del"). Click (deltr);
Add rows
$ ("#add3"). Click (function () {
$ (' <tr><td> new line </td><td><button class= ' del ' > Delete </button></td></tr > ')
Here to bind the event again to the Delete button.
. Find (". del"). Click (deltr). End ()
. Appendto ($ ("#table3 >tbody"));
});
});

Number 2nd Solution-Event Bubbling Method

Using the principle of event bubbling, we bind the ancestor element of this button to the event handler function.
And then by event.target this object to determine whether this event is triggered by the object we are looking for.
You can usually use some DOM attributes, such as Event.target.className, event.target.tagName, etc. to judge.
Copy Code code as follows:

<td><buttonclass= "del" > Delete </button></td>

JQuery (function ($) {
Delete button event bindings for table fourth
$ ("#table4"). Click (function (e) {
if (e.target.classname== "Del") {
$ (e.target). Parents ("tr"). Remove ();
};
});
Add button event bindings for table fourth
$ ("#add4"). Click (function () {
$ ("#table4 >tbody"). Append (' <tr><td> New line </td><td><button class= ' del ' > Delete </ Button></td></tr> ')
});
});


Number 3rd Solution--Copy event method

The above schemes can be said that even if you do not use the jquery library, you can also relatively easy to implement. But this scheme is more dependent on jquery. and must require jquery version 1.2 above. Low-version jquery requires plug-ins.
The above two programs are to delete the function of a lot of brain, changed a variety of triggers, binding the way. This scheme is different and can be bound in the same way as the normal static elements in Domready. But when we add a new line we change it, and we don't want to add a new line by stitching the string like the above. This time we tried to copy the DOM elements in a way. and copy it together with the bound event, copy it, and then use Find to modify the internal elements.
And, like this example, if you're going to remove all the elements from the light, that template template is necessary, and if you don't erase it, you don't need to use template. In order to prevent being mistakenly deleted, here I set the template hidden.
I used the unique clone (true) in jquery
Copy Code code as follows:

. Template{display:none;}

<trclass= "template" >
<td> here is template </td>
<td><button class= "del" > Delete </ Button></td>
</tr>
<tr>
<td> This line originally had </td>
<td><button clas s= "del" > Delete </button></td>
</tr>
<tr>
<td> This line originally had </td>
<td& Gt;<button class= "del" > Delete </button></td>
</tr>

JQuery (function ($) {
//Fifth table Deletes the button event binding
$ (#table5. del). Click (function () {
$ (this). Parents ("tr"). Remove ();
});
//Fifth Table Add-button event binding
$ ("#add5"). Click (function () {
$ ("#table5 >tbody>tr:eq (0)")
///////Copy with Event
. Cl One (TRUE)
//Remove template Tags
. removeclass ("template")
//Modify internal elements
. Find ("Td:eq (0)")
. Text ("New line")
. E nd ()
//Insert Table
. Appendto ($ ("#table5 >tbody"))
});
});

Rating

The above 4 kinds of schemes, each have pros and cons.
Plan No. 0, structure and behavior are completely not separated, and pollute the global namespace. Least recommended. So I don't see it as a plan. But for JS beginners, can be used to project emergency.
Plan 1th, it's not bad.
Plan 2nd, this method fully play the advantages of JS event bubbling. and most efficient. But at the same time, because this scheme ignores the powerful selectors of jquery, it can be cumbersome to ask for too many element attributes. You will wander among the many if conditions in the right and wrong relationships. Then I thought, I could use the $ (event.target). Is (selector) in jquery as a condition. This can greatly improve development efficiency, but slightly reduce execution efficiency.
Plan 3rd, which I think is the best way to embody the idea of separation between structure and behavior. But the disadvantage is also obvious, for jquery dependency is too high, or to write a copy with the event to copy the function, but this is obviously very difficult for beginners. But from the perspective of future trends, it is recommended to use this approach.

Specific choice of which option, there is no destiny. Specific look at your project and your JS and structure and behavior of the separation of the idea of the degree of mastery. The most suitable is the best.

Additional:

Transform the 3rd scheme into a perfect structure-behavior separation style.
First, the template element is template. He is the source of all replication, in order to prevent being mistakenly deleted, so set to invisible. If the light is not deleted, then the template element is optional. Because you can copy any one that already exists for the loop element.
Second, add a repeat to each repeating element to facilitate the deletion of the button to find this level element. This is optional, sometimes not necessary.
Finally, for each element to be modified add a class, easy to find. Like I'm home here. Content classes, new additions can modify the values inside.
Such a perfect separation of the structure and behavior of the case is completed.
Copy Code code as follows:

<tableid= "Table6" >
<tbody id= "Tbody6" >
<tr class= "Template Repeat" >
&LT;TD class= "Content" > here is the template </td>
<td><button class= "del" > Delete </button></td>
</tr>
&LT;TR class= "Repeat" >
&LT;TD class= "Content" > this line originally has </td>
<td><button class= "del" > Delete </button></td>
</tr>
&LT;TR class= "Repeat" >
&LT;TD class= "Content" > this line originally has </td>
<td><button class= "del" > Delete </button></td>
</tr>
</tbody>
<tfoot>
<tr>
<td> </td>
<td><button id= "Add6" > Add </button></td>
</tr>
</tfoot>
</table>

JQuery (function ($) {
Delete button event bindings for table sixth
$ ("#tbody6. Del"). Click (function () {
$ (this). Parents (". Repeat"). Remove ();
});
Add button event bindings for table sixth
$ ("#add6"). Click (function () {
$ ("#tbody6 >.template")
Copy together with events
. Clone (True)
Remove Template Tags
. Removeclass ("template")
modifying internal elements
. Find (". Content")
. Text (New line)
. End ()
Insert Table
. Appendto ($ ("#tbody6"))
});
});

Similarly, this JS also applies to the following HTML structure
Copy Code code as follows:

<ulid= "Tbody6" >
<li class= "Template Repeat" >
<span class= "Content" > here is the template </span>
<span><button class= "del" > Delete </button></span>
</li>
<li class= "Repeat" >
<span class= "Content" > this line originally has </span>
<span><button class= "del" > Delete </button></span>
</li>
<li class= "Repeat" >
<span class= "Content" > this line originally has </span>
<span><button class= "del" > Delete </button></span>
</li>
</ul>

<script type= "Text/javascript" ></script>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.