问题
I am trying to add and remove table rows with jQuery, added rows contain a remove link, which for some reason doesn't work on the generated elements, even though I use on.
Here my code:
$("#target").click(function() {
$('#myTable tr:last').after('<tr><td>Bla</td><td><div class="remove">REMOVE</div></td></tr>');
});
$(".remove").on('click', function(event) {
$(this).parent().parent().remove();
});
http://jsbin.com/ucopun/1/
What could be the problem?
The remove link is supposed to remove the whole row in which it is located.
回答1:
When you use on()
, you still need to bind the event to a container element that exists on the page already. I think this is what you want:
$("#myTable").on('click', '.remove', function(event) {
$(this).parent().parent().remove();
});
回答2:
You were almost there. See this jsFiddle example.
$("#myTable").on('click', '.remove', function(event) {
$(this).closest('tr').remove();
});
Since you're adding elements that don't exist when the code runs, you need to use .on()
to bind to an element that does exist when the code runs.
As the docs state:
Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on(). To ensure the elements are present and can be selected, perform event binding inside a document ready handler for elements that are in the HTML markup on the page. If new HTML is being injected into the page, select the elements and attach event handlers after the new HTML is placed into the page.
Also, I find .closest('tr')
easier to follow than .parent().parent()
回答3:
I would bind the event to the table and delegate it to the button
Reference: http://api.jquery.com/delegate/
$("#myTable").delegate('.remove','click' , function(event) {
$(this).closest('tr').remove();
});
EDIT: seems like delegate is superseeded by on (As of jQuery 1.7 - reference http://api.jquery.com/on/).
回答4:
Use live function
$('.remove',$("#myTable")).live('click',function(){
$(this).parents('tr:first').remove();
});
http://jsfiddle.net/B8wSq/2/
来源:https://stackoverflow.com/questions/13844202/trying-to-add-and-remove-table-rows-with-jquery