jquery new Element event binding problem [go]

Source: Internet
Author: User

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

    1. JQuery (function ($) {
    2. A Delete button has been initialized to initialize the binding delete event
    3. $ (". Del"). Click (function () {
    4. $ (this). Parents ("tr"). Remove ();
    5. });
    6. });

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!

    1. <td><buttononclick= "deltr (This)" > Delete </button></td>
    1. JQuery (function ($) {
    2. Adding rows
    3. $ ("#add2"). Click (function () {
    4. $ ("#table2 >tbody"). Append (' <tr><td> new row </td><td><button nclick= ' deltr (this) ' > delete </button></td></tr> ')
    5. });
    6. });
    7. The function to delete the row must be placed outside the Domready function
    8. function deltr (delbtn) {
    9. $ (DELBTN). Parents ("tr"). Remove ();
    10. };

=============================
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.

    1. <td><buttonclass= "del" > Delete </button></td>
    1. JQuery (function ($) {
    2.    //Define Delete button event bindings
    3.    //write inside to prevent polluting the global namespace
    4.    function deltr () {
    5.         $ (this). Parents ("tr"). Remove ();
    6.    };
    7.    //already has a Delete button to initialize the binding delete event
    8.     $ ("#table3. Del"). Click (deltr);
    9.    //Add lines
    10.     $ ("#add3"). Click (function () {
    11.         $ (' <tr><td> New line </td ><td><button class= "del" > Delete </button></td></tr> ')
    12.            //here to remove the button to bind the event again.
    13.            . Find (". del"). Click (deltr). End ()
    14.       &NBSP ;    . AppendTo ($ ("#table3 >tbody"));
    15.    });
    16. });

=============================
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.

    1. <td><buttonclass= "del" > Delete </button></td>
    1. JQuery (function ($) {
    2. Delete button event bindings for fourth table
    3. $ ("#table4"). Click (function (e) {
    4. if (e.target.classname== "Del") {
    5. $ (e.target). Parents ("tr"). Remove ();
    6. };
    7. });
    8. Add button event bindings for the fourth table
    9. $ ("#add4"). Click (function () {
    10. $ ("#table4 >tbody"). Append (' <tr><td> new row </td><td><button class= ' del ' > Delete </ Button></td></tr> ')
    11. });
    12. });
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)
    1. . Template{display:none;}
    1. <trclass= "Template" >
    2. <td> here is the template </td>
    3. <td><button class= "del" > Delete </button></td>
    4. </tr>
    5. <tr>
    6. <td> This line turns out to have </td>
    7. <td><button class= "del" > Delete </button></td>
    8. </tr>
    9. <tr>
    10. <td> This line turns out to have </td>
    11. <td><button class= "del" > Delete </button></td>
    12. </tr>
  1. JQuery (function ($) {
  2. Delete button event bindings for fifth table
  3. $ ("#table5. Del"). Click (function () {
  4. $ (this). Parents ("tr"). Remove ();
  5. });
  6. Add button event bindings for the fifth table
  7. $ ("#add5"). Click (function () {
  8. $ ("#table5 >tbody>tr:eq (0)")
  9. Copy together with events
  10. . Clone (True)
  11. Remove Template Markers
  12. . Removeclass ("template")
  13. modifying inner elements
  14. . Find ("Td:eq (0)")
  15. . Text ("New Row")
  16. . End ()
  17. Insert Table
  18. . AppendTo ($ ("#table5 >tbody"))
  19. });
  20. });

=============================
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.

  1. <tableid= "Table6" >
  2. <tbody id= "Tbody6" >
  3. <tr class= "Template Repeat" >
  4. <TD class= "Content" > here is the template </td>
  5. <td><button class= "del" > Delete </button></td>
  6. </tr>
  7. <TR class= "Repeat" >
  8. <TD class= "Content" > This line turns out to have </td>
  9. <td><button class= "del" > Delete </button></td>
  10. </tr>
  11. <TR class= "Repeat" >
  12. <TD class= "Content" > This line turns out to have </td>
  13. <td><button class= "del" > Delete </button></td>
  14. </tr>
  15. </tbody>
  16. <tfoot>
  17. <tr>
  18. <td>&nbsp;</td>
  19. <td><button id= "Add6" > Add </button></td>
  20. </tr>
  21. </tfoot>
  22. </table>
  1. JQuery (function ($) {
  2. Delete button event bindings for sixth table
  3. $ ("#tbody6. Del"). Click (function () {
  4. $ (this). Parents (". Repeat"). Remove ();
  5. });
  6. Add button event bindings for the sixth table
  7. $ ("#add6"). Click (function () {
  8. $ ("#tbody6 >.template")
  9. Copy together with events
  10. . Clone (True)
  11. Remove Template Markers
  12. . Removeclass ("template")
  13. modifying inner elements
  14. . Find (". Content")
  15. . Text ("New Row")
  16. . End ()
  17. Insert Table
  18. . AppendTo ($ ("#tbody6"))
  19. });
  20. });

Similarly, this JS also applies to the following HTML structure

      <ulid=" Tbody6 ";
    1.    <li class= "Template repeat";
    2.        <span class= "Content" > here is the template </span>
    3.        <span><button class= "del" > Delete </button></span>
    4.    </li>
    5.    <li class= "repeat";
    6.        <span class= "Content" > This line turns out to have </span>
    7.        <span><button class= "del" > Delete </button></span>
    8.    </li>
    9.    <li class= "repeat";
    10.        <span class= "Content" > This line turns out to have </span>
    11.        <span><button class= "del" > Delete </button></span>
    12.    </li>
    13. </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.