What is the best way to remove a table row with jQuery?

用jQuery去除表格行的最佳方法是什么?


You're right:

$('#myTableRow').remove();

This works fine if your row has an id , such as:

<tr id="myTableRow"><td>blah</td></tr>

If you don't have an id , you can use any of jQuery's plethora of selectors.


@Eikern

If you're gonna use jQuery, use jQuery man!

$('#myTable tr').click(function(){
    $(this).remove();
    return false;
});

Assuming you have a button/link inside of a data cell in your table, something like this would do the trick...

$(".delete").live('click', function(event) {
    $(this).parent().parent().remove();
});

This will remove the parent of the parent of the button/link that is clicked. You need to use parent() because it is a jQuery object, not a normal DOM object, and you need to use parent() twice, because the button lives inside a data cell, which lives inside a row....which is what you want to remove. $(this) is the button clicked, so simply having something like this will remove only the button:

$(this).remove();

While this will remove the data cell:

    $(this).parent().remove();

If you want to simply click anywhere on the row to remove it something like this would work. You could easily modify this to prompt the user or work only on a double-click:

$(".delete").live('click', function(event) {
    $(this).parent().remove();
});

Hope that helps...I struggled on this a bit myself.

链接地址: http://www.djcxy.com/p/3932.html

上一篇: 在JavaScript控制台中包含jQuery

下一篇: 用jQuery去除表格行的最佳方法是什么?