InsertAfter () is added by doubling.

I am trying to add tr after some certian tr and I am using this code. but it is added by doubling, the first time only 1, the second time 2 and the third time 6 ... can someone help me, where does this cause this problem? I just want to add only one tr per click.

 function einfugen(){ $('#append_tr').bind('click', function(){ $('<tr><td>new td</td></tr>').insertAfter('#append_tr'); }); } <tr id="append_tr"> some data </td> 

EDIT : here is my binding code:

 <tr id="append_tr"><td> <a onclick="einfugen()"> + add </a> </td></tr> 

thanks for the help

+4
source share
3 answers

The einfugen() function declares a click handler and is called from the click event here:

 <tr id="append_tr"><td> <a onclick="einfugen()"> + add </a> </td></tr> 

The more you click on it, the more click handler is added. Instead, you can remove the declaration of the einfugen() function, but instead move the contents to the DOM ready function:

 $(function() { $('#append_tr').on('click', function(){ $('<tr><td>new td</td></tr>').insertAfter('#append_tr'); }); }); 

Having a registered click handler eliminates the need for inline onclick handler code.

+2
source

You can call the function several times.

Do not use bind and use on (jQuery 1.7):

 $('#append_tr').on('click', function(){ $('<tr><td>new td</td></tr>').insertAfter('#append_tr'); }); 

http://api.jquery.com/bind/

From your edit:

  <a onclick="einfugen()"> 

This is problem. You reset the event handler every time the link is clicked.

Using the following structure, you can do:

 $("#append_tr").click(function() { $("#table").append("<tr><td>New row!</td></tr>"); }); 

http://jsfiddle.net/mBNbZ/

+3
source

It looks like you call einfugen more than once. If you only call it once, it will work ( Demo ).

EDIT: From your update, yes, you bind the listener every time you click the add link. You are misleading an action that would be reasonable in an onclick to associate a listener with a fire in this event.

Your insertAfter does not start when einfugen starts. einfugen simply adds a listener that instructs that this code is einfugen whenever a click occurs. So the call can be made once, initially, and then your listener will always be there. It should not be added each time you click.

You can first link the listener like this:

 $(function() { $('#append_tr').bind('click', function(){ $('<tr><td>new td</td></tr>').insertAfter('#append_tr'); }); }); 

Where $(function() { ... }); is a shorthand for running a function on DOMReady , i.e. as soon as all DOM nodes are available to access the script.

Demo

+2
source

All Articles