Original: http://www.cnblogs.com/linzheng/archive/2010/10/17/1853568.html
JS event monitoring and CSS is not the same, as long as the CSS set the style, whether it is the original or new additions, have the same performance. While event snooping is not, you have to bind each element individually to an event.
A common example is when working with tables. There is a delete button at the end of each line, so you can delete this line by point.
<table>
<tbody>
<tr>
<td> This line turns out to have </td>
<td><buttonclass= "del" > Delete </button></td>
</tr>
<tr>
<td> This line turns out to have </td>
<td><buttonclass= "del" > Delete </button></td>
</tr>
</tbody>
</table>
Normally, I would be so bound
- JQuery (function ($) {
- A Delete button has been initialized to initialize the binding delete event
- $ (". Del"). Click (function () {
- $ (this). Parents ("tr"). Remove ();
- });
- });
Everything is perfect for the delete button that existed before Domready. However, if you add a few lines with JS dynamically after Domready, those buttons in the new lines will lose any effect.
How to solve this problem? The following 4 solutions are available:
=============================
Solution--onclick No. No. 0 method
I would normally do this if we disregard the principle of separation of structure from behavior.
Note that this function must be a global function at this time, you have to put jquery (function ($) {}) outside, put inside into a local function, the onclick in the HTML will not be called!
- <td><buttononclick= "deltr (This)" > Delete </button></td>
- JQuery (function ($) {
- Adding rows
- $ ("#add2"). Click (function () {
- $ ("#table2 >tbody"). Append (' <tr><td> new row </td><td><button nclick= ' deltr (this) ' > delete </button></td></tr> ')
- });
- });
- The function to delete the row must be placed outside the Domready function
- function deltr (delbtn) {
- $ (DELBTN). Parents ("tr"). Remove ();
- };
=============================
Number 1th Solution--Repeated binding method
That is, the event handler is bound to the existing element at the time of Domready,
And then when the newly added element is bound again.
- <td><buttonclass= "del" > Delete </button></td>
- JQuery (function ($) {
- //Define Delete button event bindings
- //write inside to prevent polluting the global namespace
- function deltr () {
- $ (this). Parents ("tr"). Remove ();
- };
- //already has a Delete button to initialize the binding delete event
- $ ("#table3. Del"). Click (deltr);
- //Add lines
- $ ("#add3"). Click (function () {
- $ (' <tr><td> New line </td ><td><button class= "del" > Delete </button></td></tr> ')
- //here to remove the button to bind the event again.
- . Find (". del"). Click (deltr). End ()
- &NBSP ; . AppendTo ($ ("#table3 >tbody"));
- });
- });
=============================
Solution number 2nd-Event bubbling method
Using the principle of event bubbling, we bind event handlers to the ancestor elements of this button.
And then by event.target this object to judge, this event is not the object we are looking for trigger.
You can usually use some DOM attributes, such as Event.target.className, Event.target.tagName, and so on to judge.
- <td><buttonclass= "del" > Delete </button></td>
- JQuery (function ($) {
- Delete button event bindings for fourth table
- $ ("#table4"). Click (function (e) {
- if (e.target.classname== "Del") {
- $ (e.target). Parents ("tr"). Remove ();
- };
- });
- Add button event bindings for the fourth table
- $ ("#add4"). Click (function () {
- $ ("#table4 >tbody"). Append (' <tr><td> new row </td><td><button class= ' del ' > Delete </ Button></td></tr> ')
- });
- });
Solution number 3rd-Replication event method
The above scenarios can be said that even if you do not use the jquery library, you can be relatively easy to implement. But this approach is much more dependent on jquery. And you have to ask for jquery version 1.2 or more. The low version of jquery requires plugins.
The above two scenarios are a lot of brain to delete function, change a variety of trigger, binding way. This scheme is different and can be bound at the same time as the static elements of Domready. But when we add a new line, we change it, no longer want to join the string to add a new line. This time we try to copy the DOM elements by using the way. and copy it along with the bound events, copy it, and then use Find to modify the internal elements.
At the same time, as in this example, if you would remove all the elements from the light, the template is a must, and if it is not erased, then it may not be necessary to use templates. To prevent accidental deletion, I set the template hidden here.
I used clone specific to jquery (true)
- . Template{display:none;}
- <trclass= "Template" >
- <td> here is the template </td>
- <td><button class= "del" > Delete </button></td>
- </tr>
- <tr>
- <td> This line turns out to have </td>
- <td><button class= "del" > Delete </button></td>
- </tr>
- <tr>
- <td> This line turns out to have </td>
- <td><button class= "del" > Delete </button></td>
- </tr>
- JQuery (function ($) {
- Delete button event bindings for fifth table
- $ ("#table5. Del"). Click (function () {
- $ (this). Parents ("tr"). Remove ();
- });
- Add button event bindings for the fifth table
- $ ("#add5"). Click (function () {
- $ ("#table5 >tbody>tr:eq (0)")
- Copy together with events
- . Clone (True)
- Remove Template Markers
- . Removeclass ("template")
- modifying inner elements
- . Find ("Td:eq (0)")
- . Text ("New Row")
- . End ()
- Insert Table
- . AppendTo ($ ("#table5 >tbody"))
- });
- });
=============================
General comments
The above 4 kinds of programs, each have pros and cons.
Scenario No. 0, the structure and behavior are completely separate and pollute the global namespace. Least recommended. So I don't see it as a scheme. But for JS beginners, can be used for project emergency.
Plan 1th, no good, nothing bad
Program 2nd, this method fully play the advantages of the JS event bubbling. and the most efficient. But at the same time, because this scheme ignores the powerful jquery selector, it can be cumbersome if the element attributes involved are too demanding. You will wander among the many if conditions of the non-relationship. Later I remember that you can use $ (event.target). Is (selector) in jquery as a condition. This can greatly improve development efficiency, but slightly reduces execution efficiency.
Program number 3rd, which I think is the best way to embody the idea of separation of structure from behavior. But it is also obvious that the dependency on jquery is too high to write a copy of the function that replicates with the event, but it is also obviously very difficult for beginners. However, from the perspective of future trends, it is recommended to use this scheme.
Specific choice of which program, there is no destiny. Depending on your project and your JS and the structure and behavior of the idea of separation of the degree of mastery. The best is what is right.
=============================
Additional:
Transform the 3rd scheme into a perfect pattern of structural behavior separation.
First, there are template elements with templates. He is the source of all replication, to prevent accidental deletion, so set to invisible. If the light is not removed, then this template element is optional. Because you can copy any one that already exists for the loop element.
Next, add a repeat to each repeating element, which is handy for deleting the button to find this level of element. This is optional and sometimes not necessary.
Finally, add a class to each element you want to modify, so it's easy to find with find. Like I'm home. Content class, new additions can be modified inside the value.
The case for a perfect separation between structure and behavior is complete.
- <tableid= "Table6" >
- <tbody id= "Tbody6" >
- <tr class= "Template Repeat" >
- <TD class= "Content" > here is the template </td>
- <td><button class= "del" > Delete </button></td>
- </tr>
- <TR class= "Repeat" >
- <TD class= "Content" > This line turns out to have </td>
- <td><button class= "del" > Delete </button></td>
- </tr>
- <TR class= "Repeat" >
- <TD class= "Content" > This line turns out to have </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 sixth table
- $ ("#tbody6. Del"). Click (function () {
- $ (this). Parents (". Repeat"). Remove ();
- });
- Add button event bindings for the sixth table
- $ ("#add6"). Click (function () {
- $ ("#tbody6 >.template")
- Copy together with events
- . Clone (True)
- Remove Template Markers
- . Removeclass ("template")
- modifying inner elements
- . Find (". Content")
- . Text ("New Row")
- . End ()
- Insert Table
- . AppendTo ($ ("#tbody6"))
- });
- });
Similarly, this JS also applies to the following HTML structure
<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 turns out to have </span>
- <span><button class= "del" > Delete </button></span>
- </li>
- <li class= "repeat";
- <span class= "Content" > This line turns out to have </span>
- <span><button class= "del" > Delete </button></span>
- </li>
- </ul>
<script type= "Text/javascript" ></SCRIPT>