在jQuery中添加表格行

2022-01-29 00:00:00 html-table jquery javascript

在 jQuery 中将额外的一行作为最后一行添加到表中的最佳方法是什么?

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

这可以接受吗?

$('#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)?

推荐答案

你建议的方法并不能保证给你你正在寻找的结果 - 如果你有一个 tbody 例如:

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>

你会得到以下结果:

<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>');

您可以在 after() 方法中包含任何内容,只要它是有效的 HTML,包括上面示例中的多行.

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

更新:在最近有此问题的活动后重新访问此答案.eyelidlessness 很好地说明了 DOM 中总会有一个 tbody ;这是真的,但前提是至少有一行.如果您没有行,则不会有 tbody,除非您自己指定了一个.

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_ 建议附加到 tbody而不是在最后一个 tr 之后添加内容.这解决了没有行的问题,但仍然不是防弹的,因为理论上你可以有多个 tbody 元素并且行会被添加到每个元素中.

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.

权衡一切,我不确定是否有一个单一的单线解决方案可以解决所有可能的情况.您需要确保 jQuery 代码与您的标记相符.

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.

我认为最安全的解决方案可能是确保您的 table 始终在您的标记中包含至少一个 tbody,即使它没有行.在此基础上,您可以使用以下内容,无论您拥有多少行(并且还考虑多个 tbody 元素):

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>');

相关文章