I have following table structure.
<table>
<tr>
<td><a href="#"></td>
</tr>
</table>
When I click on <a>
I want to add new <tr>
next to <tr>
of which <a>
is clicked.
So the result will be:
<table>
<tr>
<td><a href="#"></td>
</tr>
<tr>
<td><a href="#"></td>
</tr>
</table>
Example:
$('a').bind('click', function(){
$('<tr><td>new td</td></tr>').insertAfter($(this).closest('tr'));
});
If you want to create a clone use:
$('a').live('click', function(){
var $this = $(this),
$parentTR = $this.closest('tr');
$parentTR.clone().insertAfter($parentTR);
});
Example link: http://www.jsfiddle.net/7A6MQ/
Basically, you create a copy from the tr element
(which includes child nodes) and insert that copy after that element. Therefore, you need the .live
binding to make sure that newly created a
elements do also invoke that click handler.
Ref.: .clone(), .insertAfter(), .live()
Also, you can write:
$('a').bind('click', function () {
$(this).closest('tr').after('<tr><td>new td<td></tr>');
});
Not so much difference but looks more readable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With