游.程 2008-10-04 21:33 采纳率: 0%
浏览 698
已采纳

在 jQuery 中添加表格行

What is the best method in jQuery to add an additional row to a table as the last row?

Is this acceptable?

$('#myTable').append('<tr><td>my data</td><td>more data</td></tr>');

Are there limitations to what you can add to a table like this (such as inputs, selects, number of rows)?

转载于:https://stackoverflow.com/questions/171027/add-table-row-in-jquery

  • 写回答

28条回答 默认 最新

  • local-host 2008-10-04 21:49
    关注

    The approach you suggest is not guaranteed to give you the result you're looking for - what if you had a tbody for example:

    <table id="myTable">
      <tbody>
        <tr>...</tr>
        <tr>...</tr>
      </tbody>
    </table>
    

    You would end up with the following:

    <table id="myTable">
      <tbody>
        <tr>...</tr>
        <tr>...</tr>
      </tbody>
      <tr>...</tr>
    </table>
    

    I would therefore recommend this approach instead:

    $('#myTable tr:last').after('<tr>...</tr><tr>...</tr>');
    

    You can include anything within the after() method as long as it's valid HTML, including multiple rows as per the example above.

    Update: Revisiting this answer following recent activity with this question. eyelidlessness makes a good comment that there will always be a tbody in the DOM; this is true, but only if there is at least one row. If you have no rows, there will be no tbody unless you have specified one yourself.

    DaRKoN_ suggests appending to the tbody rather than adding content after the last tr. This gets around the issue of having no rows, but still isn't bulletproof as you could theoretically have multiple tbody elements and the row would get added to each of them.

    Weighing everything up, I'm not sure there is a single one-line solution that accounts for every single possible scenario. You will need to make sure the jQuery code tallies with your markup.

    I think the safest solution is probably to ensure your table always includes at least one tbody in your markup, even if it has no rows. On this basis, you can use the following which will work however many rows you have (and also account for multiple tbody elements):

    $('#myTable > tbody:last-child').append('<tr>...</tr><tr>...</tr>');
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(27条)

报告相同问题?

悬赏问题

  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊
  • ¥15 安装svn网络有问题怎么办
  • ¥15 Python爬取指定微博话题下的内容,保存为txt
  • ¥15 vue2登录调用后端接口如何实现
  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?