使用Jquery选择tr by id

我正在尝试在表格中选择一个tr来删除它,但我没有选择器的运气。

表看起来像这样:

Product: Size: Colour: Qty Price Delete
Shuttle 54.95 Red 1 [X]
Shuttle 54.95 Red 1 [X]

带有产品ID的tr动态附加了jQuery,因此不确定是否会产生影响。

deleteProduct(id)函数如下所示:

 function deleteProduct(id) { $('#product_' + id).remove(); } 

点击后没有任何反应,Chrome控制台中没有错误。

在控制台中捣乱了一下:

$('#selectedproducts').html(); 返回数据$('#selectedproducts').find('#product_1').html()返回空

我会这样做的

 
Product: Size: Colour: Qty Price Delete
Shuttle 54.95 Red 1 [X]
Shuttle 54.95 Red 1 [X]

和jQuery:

 $('tr a').live('click', function () { $(this).closest('tr').remove(); }); 

这个选择器的另一种选择是

  $('tr[id^="product_"] a').live('click', function () { // you could ge the id number from the tr to do other things with var id = $(this).closest('tr').attr('id').replace("product_",""); $(this).closest('tr').remove(); }); 

这会将它限制为只有id以“product_”开头的tr

或者你可以删除带有_id结尾的项目

  $('tr[id^="product_"] a').live('click', function () { // you could ge the id number from the tr var id = $(this).closest('tr').attr('id').replace("product_",""); //then you could remove anything the that ends with _id $('[id$="_'+id+'"]').remove(); }); 

我稍微修改了代码,这是一个DEMO

您不需要内联onclics,也不需要为此function。 您需要做的就是调用this引用被点击的项目。 在下面的示例中,您单击的任何项目都将被删除。

 $('td').live('click', function() { $(this).parent().remove(); }) 

查看http://jsfiddle.net/aswae/2/上的工作示例

您还可以插入删除按钮,然后选择通过单击按钮删除。

查看http://jsfiddle.net/aswae/4/上的更新示例

你的deleteProduct函数接受一个id参数,但onclick处理程序中没有任何地方定义了该参数。 试试这个:

HTML

   

JavaScript的

 function deleteProduct(elt) { $(elt).closest('tr[id]').remove(); } 

演示1

正如评论中指出的那样,你的

标签中也有一些无效的标记。


也就是说,你正在使用jQuery,所以没有理由不编写不引人注目的JavaScript 。 完全摆脱onclick属性,并使用它:

 $('#selectedproducts a').live('click', function () { $(this).closest('tr[id]').remove(); }); 

演示2


如果您希望使用选择器更具体,这将适用于当前标记:

 $('#selectedproducts td:last > a').live('click', function () { $(this).closest('tr[id]').remove(); }); 

演示3

将您的[X]链接更改为:

 [X] 

你的jQuery:

 $(".delete").click(function() { $(this).parents("tr").remove(); }); 

如果您确实使用deleteProduct(id) ,则需要将ID替换为该行的编号。

您也可以在DOM树中跳过几个级别(删除父级的父级),而不是手动输入ID。 我相信你可以把onclick="$(this).parent().parent().remove()"改为。