且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用Jquery选择tr by id

更新时间:2023-12-05 12:11:46

我会这样做

<table width="301" border="0" cellspacing="5" cellpadding="0" id="selectedproducts" =="">
      <tbody>
        <tr>
          <th width="56" scope="col">Product:</th>
          <th width="48" scope="col">Size:</th>
          <th width="71" scope="col">Colour:</th>
          <th width="41" scope="col">Qty</th>
          <th width="55" scope="col">Price</th>
          <th width="55" scope="col">Delete</th>
        </tr>
        <tr id="product_1">
          <td>Shuttle</td>
          <td>54.95</td>
          <td>Red</td>
          <td>1</td>
          <td></td>
          <td><a>[X]</a></td>
        </tr>
        <tr id="product_2">
          <td>Shuttle</td>
          <td>54.95</td>
          <td>Red</td>
          <td>1</td>
          <td></td>
          <td><a>[X]</a></td>
        </tr>
      </tbody>
 </table>

和jQuery:

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

此选择器的另一种选择是

another alternative to this selector would be

 $('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();
});

这会将其限制为仅以product _开头的那个

this would restrict it to only tr that whose id starts with "product_"

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

alternately you could delete item with an _id ending like this

 $('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

I changed the code slightly here is a DEMO