Add table row in jQuery(在jQuery中添加表格行)
问题描述
在 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>');
这篇关于在jQuery中添加表格行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在jQuery中添加表格行
基础教程推荐
- 响应更改 div 大小保持纵横比 2022-01-01
- 在for循环中使用setTimeout 2022-01-01
- 悬停时滑动输入并停留几秒钟 2022-01-01
- 当用户滚动离开时如何暂停 youtube 嵌入 2022-01-01
- 角度Apollo设置WatchQuery结果为可用变量 2022-01-01
- 在 JS 中获取客户端时区(不是 GMT 偏移量) 2022-01-01
- 有没有办法使用OpenLayers更改OpenStreetMap中某些要素 2022-09-06
- Karma-Jasmine:如何正确监视 Modal? 2022-01-01
- 动态更新多个选择框 2022-01-01
- 我什么时候应该在导入时使用方括号 2022-01-01