在jQuery中添加表行 [英] Add table row in jQuery

查看:191
本文介绍了在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>

您最终会得到以下结果:

You would end up with the following:

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

因此我推荐这种方法:

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

您可以在之后包含任何内容()方法,只要它是有效的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.

我认为最安全的解决方案可能是确保您的在标记中始终包含至少一个 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中添加表行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆