如何使用 jQuery 在表格中间添加行?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2560613/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to add rows in middle of a table with jQuery?
提问by understack
I've a table which has customers names along with the products they purchased with their prices. So there are multiple records for each customer. This table is simple 3 column table : name, product and price.
我有一张表,上面有客户姓名以及他们购买的产品及其价格。因此,每个客户都有多个记录。该表是简单的 3 列表:名称、产品和价格。
What I want to do is:
我想做的是:
Put all records belonging to one customer together (I've done it) and just after these rows add one new extra row which would just show total price of all the products each customer has purchased. This row would have empty cell in name and product column. And would have total in price column.
将属于一个客户的所有记录放在一起(我已经完成了),并在这些行之后添加一个新的额外行,该行仅显示每个客户购买的所有产品的总价。此行在名称和产品列中会有空单元格。并且在价格栏中会有总计。
EDIT
编辑
It's just a plain simple table without any class or ids. customer wise grouped Table is generated by php. So I've a table like this
它只是一个简单的表,没有任何类或 ID。客户明智的分组表由 php 生成。所以我有一张这样的桌子
<table>
<tr>
<td> name1 </td>
<td> product1 </td>
<td> 100 </td>
</tr>
<tr>
<td> name1 </td>
<td> product2 </td>
<td> 200 </td>
</tr>
<tr>
<td> name2 </td>
<td> product3 </td>
<td> 50 </td>
</tr>
<tr>
<td> name2 </td>
<td> product1 </td>
<td> 100 </td>
</tr>
</table>
And I want to convert this to :
我想将其转换为:
<table>
<tr>
<td> name1 </td>
<td> product1 </td>
<td> 100 </td>
</tr>
<tr>
<td> name1 </td>
<td> product2 </td>
<td> 200 </td>
</tr>
<!-- New row -->
<tr>
<td> </td>
<td> </td>
<td> 300 </td>
</tr>
<tr>
<td> name2 </td>
<td> product3 </td>
<td> 50 </td>
</tr>
<tr>
<td> name2 </td>
<td> product1 </td>
<td> 100 </td>
</tr>
<!-- New row -->
<tr>
<td> </td>
<td> </td>
<td> 150 </td>
</tr>
</table>
回答by jAndy
var prize = 1 * 1;
var newrow = $('<tr><td></td><td></td><td>' + prize + '</td></tr>');
$('#rowid').after(newrow);
or
或者
newrow.insertAfter('#rowid');
where #rowid
is an id from a row you want to append a new line.
#rowid
您要追加新行的行中的 id在哪里。
回答by geowa4
Using jQuery you can select all rows where the username is contained within one of it's descendant elements. I'm assuming usernames are unique.
使用 jQuery,您可以选择用户名包含在其后代元素之一中的所有行。我假设用户名是唯一的。
$("tr:contains('" + username + "')")
Now, get the last one
现在,得到最后一个
$("tr:contains('" + username + "')").last()
And use the after
function to insert your new row.
并使用该after
函数插入新行。