简体   繁体   English

使用jQuery删除多个表行

[英]Remove several table rows using jQuery

I need to remove three rows of a table when a link in the first row is clicked. 当单击第一行中的链接时,我需要删除表的三行。

The rows are created dynamically using jQuery and pre-pended to the table as below. 这些行是使用jQuery动态创建的,并预先填充到表中,如下所示。

var ups='';
        ups+='<tr data-file='+file_id+'>';
        ups+='<td width="40%">'+gl_file_name1+'</td><td>'+gl_upload_date1+'</td>';
        ups+='<td>'+gl_upload_desc+'</td>';
        ups+='<td><a href="sym.php?doc_id='+file_id+'" class="view2_fl">VIEW FILE</a> | <a href="javascript:void(0);" data-file='+file_id+' data-job='+job_id+' class="del2_fl">DELETE</a></td></tr>';
        ups+='<tr><td>'+priority+'</td><td>'+price+'</td><td>'+tender+'</td><td>&nbsp;</td></tr>';
        ups+='<tr class="bottom-row"><td colspan="4">'+notes+'</td><tr>';

        $(ups).prependTo('.app_table');

This is looped for as many times as there are 'files'. 这与'文件'一样多次循环。

When the DELETE link is pressed I need to delete all three rows. 按下DELETE链接时,我需要删除所有三行。 So far I have managed to delete the first row using the code below: 到目前为止,我已设法使用以下代码删除第一行:

$(this).closest("tr").remove();

I have tried to use .next() but this did not seem to work. 我曾尝试使用.next(),但这似乎不起作用。

Get the row with the link, and from there you can get the next rows and add to the jQuery object, and remove all three in one go: 获取带有链接的行,然后从那里获取下一行并添加到jQuery对象,并一次性删除所有三个:

var tr = $(this).closest("tr");
tr.add(tr.next()).add(tr.next().next()).remove();

By first getting all three rows you don't have the problem that you want to find a row that is next to a row that you have already removed. 通过首先获取所有三行,您不会遇到要查找已删除的行旁边的行的问题。

Just another idea, you could use a selector like gt. 只是另一个想法,你可以使用像gt这样的选择器。

For example: 例如:

$('tr:gt(1)').remove()

Should remove the rows after the first. 应该在第一行之后删除行。

$('tr:eq(0)').remove()

Should remove the first row 应该删除第一行

Reggards Reggards

next() ought to work I think. 我认为下一个()应该工作。 Try saving the reference to the closest tr and removing the others first, eg 尝试将引用保存到最近的tr并首先删除其他tr,例如

var $tr = $(this).closest("tr");
$tr.next("tr").remove();
$tr.next("tr").remove();
$tr.remove();

Demo fiddle: http://jsfiddle.net/rupw/tZMgs/ 演示小提琴: http//jsfiddle.net/rupw/tZMgs/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM