The approach you suggest is not guaranteed to give you the result you're looking for - what if you had a tbody
for example:
(您建议的方法无法保证为您提供您正在寻找的结果 - 例如,如果您有一个tbody
:)
<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.
(您可以在after()
方法中包含任何内容,只要它是有效的HTML,包括上面示例中的多行。)
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; (eyelidless是一个很好的评论,在DOM中总会有一个tbody
;)
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. (如果你没有行,就没有tbody
,除非你有自己指定的一个。)
DaRKoN_ suggests appending to the tbody
rather than adding content after the last tr
.
(DaRKoN_ 建议附加到tbody
而不是在最后一个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. (这解决了没有行的问题,但仍然没有防弹,因为理论上你可以有多个tbody
元素,并且行将被添加到每个行。)
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. (您需要确保jQuery代码与您的标记一致。)
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.
(我认为最安全的解决方案可能是确保您的table
始终在您的标记中包含至少一个tbody
,即使它没有行。)
On this basis, you can use the following which will work however many rows you have (and also account for multiple tbody
elements): (在此基础上,您可以使用以下工作,但是您可以使用多行(并且还可以考虑多个tbody
元素):)
$('#myTable > tbody:last-child').append('<tr>...</tr><tr>...</tr>');