如何在TBODY的第一行引用特定的TD并使用Jquery更改同一行的类?

时间:2012-03-24 05:48:45

标签: jquery dom

我有一个像这样的HTML表

HTML

  <table id="myTable">
    <thead>
    <tr class="item">
    <td>ID</td>
    <td>Name</td>
    <td>Phone</td>
    <td>Action</td>
    </thead>
    <tbody>
    <tr class="item">
    <td>1</td>
    <td>John Collins</td>
    <td>9089898989</td>
    <td><button>Save</button></td>

    </tr>
    <tr class="item">
    <td>1</td>
    <td>Janine Godwin</td>
    <td>Janine Godwin</td>
    <td>43433434</td>
    <td><button>Save</button></td>
    </tr>
    </tbody>

    </table>

我想删除tbody标记内第一行中的最后一个TD(按钮),并将同一行的类从“item”更改为“sample”。我怎么能用Jquery做到?

2 个答案:

答案 0 :(得分:2)

  1. Get the table:
    $('#myTable')
  2. Get the <tbody>:
    $('#myTable > tbody')
  3. Get the first row in the <tbody>:
    $('#myTable > tbody > tr:first')
  4. 更改该行的课程from 'item' to 'sample'
    $('#myTable > tbody > tr:first').removeClass('item').addClass('sample')
  5. Get the last <td> in the first row in the <tbody>:
    $('#myTable > tbody > tr:first > td:last')
  6. Remove that last <td>:
    $('#myTable > tbody > tr:first > td:last').remove()
  7. 把它们放在一起:

    $('#myTable > tbody > tr:first')
        .removeClass('item')
        .addClass('sample')
        .children('td:last')
        .remove();
    

答案 1 :(得分:0)

我认为这符合您的要求,但我建议您阅读Jquery的文档。

$('tbody tr.item:first')
    .attr('class', 'sample')
    .find('td button').text('change me')

第一部分获取您想要的行,第二部分更改类,第三部分找到按钮并更改它(但是,您没有提到如何更改它)。