I'm adding the <tr>
via a Javascript var:
var txtBox = "<tr id='dynTR'><td><input type='text' class='textBoxes' /></td><td><input type='text' class='textBoxes' value='0' /></td><td><input type='button' value='-' /></td></tr>";
With my function being:
function AddTR(table) {
$(table).append(txtBox);
}
My table structure (along with开发者_如何学JAVA the button for the function) in the HTML being:
<table id="tblTest" class="testTable">
<thead>
<tr>
<td>Product</td>
<td>Quantity</td>
<td>Remove TR</td>
</tr>
</thead>
<tbody>
</tbody>
</table>
<br />
<input type="Button" id="btnTest" value="Add Table Row" onclick="AddTR($('#tblTest'))" />
So how do I go about using the .remove()
function in jQuery to get rid of the parent tag without accidentally removing all <tr id='dynTR'>
tags?
Considering this one is the remove button:
<input type='button' value='-' />
The following will do:
$('#tblTest input[type="button"]').click(function () {
$(this).closest('tr').remove();
});
I'd suggest you use jQuery event handlers instead of using inline onclick
and friends. $(this)
is the jQuery object of the button that was clicked, .closest()
will look in the parents of the button and find the first tr
, then remove it.
jsFiddle by @ShadowWizard
The best way would be to change the HTML for your remove button:
<input type='button' value='-' class='removeButton' />
so you can target your remove button like this:
$('#tblTest .removeButton').click(...
This is better because with the previous example, every possible input type="button"
in the table would get the event, even though we just need it on these special ones (not a problem if there are no other buttons in the table).
bazmegakapa answer should do the trick. Also you should really avoid using inline Javascript, it's generally bad practise. Instead do:
$('#btnTest').click(function() { AddTR($('#tblTest')); });
Also to keep up with the convention of jQuery using the correct scope of the element object, you could do:
$('#btnTest').click(function() { AddTR.call($('#tblTest')[0]); });
Then in your AddTR function you can simply reference the element table as this
function AddTR() {
$(this).append(txtBox);
}
It keeps things predictable and follows the same convention.
Hang on a minute....
In theory although the AddTR()
function is adding a table row, it's a bit misleading because all it's doing is just appending an element to that context. What you really want to do is just what the function says; add a table row! instead your doing
var txtBox = "<tr id='dynTR'><td><input type='text' class='textBoxes' /></td><td><input type='text' class='textBoxes' value='0' /></td><td><input type='button' value='-' /></td></tr>";
Which is rather ugly and will cause some changes if you change your table row structures. Instead, use .clone
to help you:
function AddTR() {
$(this).append($('tr:last').clone());
}
See fiddle: http://jsfiddle.net/garreh/6NUK3/1/
精彩评论