doniyor
doniyor

Reputation: 37876

insertAfter() is appending by doubling

i am trying to append tr after some certian tr and i use this code. but it is appending by doubling, first time only 1, second time 2 and third time 6... can someone help me out where this is causing this issue? 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 help

Upvotes: 4

Views: 701

Answers (3)

Darren
Darren

Reputation: 70728

You may be calling the function numerous times.

Don't 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()"> 

Is the problem. You are rebinding an event handler each time the link is clicked.

Using the following structure you could do:

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

http://jsfiddle.net/mBNbZ/

Upvotes: 3

Ja͢ck
Ja͢ck

Reputation: 173562

Your einfugen() function declares the click handler and it's called from the click event here:

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

The more you click it, the more click handlers are attached. What you could do instead is remove the einfugen() function declaration but move the contents into the DOM ready function instead:

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

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

Upvotes: 2

David Hedlund
David Hedlund

Reputation: 129792

It sounds like you're calling einfugen more than once. If you only call it once, it will work (Demo).

EDIT: From your update, yes, you're binding a listener every time the 'add' link is clicked. You're confusing firing an action that would be sensible in onclick, with binding a listener to fire at a given event.

Your insertAfter isn't run when einfugen is run. einfugen just adds a listener that instructs that code to run whenever a click happens. So that call can be made once, initially, and then your listener will always be there. It shouldn't be added at every click.

You could bind the listener initially like this:

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

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

Demo.

Upvotes: 2

Related Questions