我试图在
的许多表的开头插入一行myList = [ “comments”: [“1, 2”], “comments”:[], “comment”: [“2”, “2”, “newElement"], “comment”: [“newElement”] ]
仅将新$('table > tbody > tr:first').before('<tr><td>Stuff</td></tr>');
添加到第一个表和
tr
再次将所有新$("tbody").each(function() {
$('table > tbody > tr:first').before('<tr><td>Stuff</td></tr>');
});
添加到第一个表格。我该如何解决这个问题?
tr
&#13;
$("tbody").each(function() {
$('table > tbody > tr:first').before('<tr><td>Stuff</td></tr>');
});
$('table > tbody > tr:first').before('<tr><td>Stuff</td></tr>');
&#13;
table,
th,
td {
border: 1px solid #eee;
}
&#13;
答案 0 :(得分:4)
使用$(this)
来引用每个表格。
$("tbody ").each(function() {
$(this).before('<tr><td>Stuff</td></tr>');
});
&#13;
table,
th,
td {
border: 1px solid #eee;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tbody>
<tr>
<td>January</td>
<td>$100</td>
</tr>
<tr>
<td>February</td>
<td>$80</td>
</tr>
</tbody>
</table>
<table>
<tbody>
<tr>
<td>January</td>
<td>$100</td>
</tr>
<tr>
<td>February</td>
<td>$80</td>
</tr>
</tbody>
</table>
<table>
<tbody>
<tr>
<td>January</td>
<td>$100</td>
</tr>
<tr>
<td>February</td>
<td>$80</td>
</tr>
</tbody>
</table>
<table>
<tbody>
<tr>
<td>January</td>
<td>$100</td>
</tr>
<tr>
<td>February</td>
<td>$80</td>
</tr>
</tbody>
</table>
&#13;
P.S - 如果您想在tbody
内填写,可以使用$(this).find("tr:first").before('<tr><td>Stuff</td></tr>');
答案 1 :(得分:2)
$("tbody").each(function() {
// I don't want to insert before the tbody,
// I want to insert before the first row.
$(this).find("tr:first").before('<tr><td>Stuff</td></tr>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tbody>
<tr>
<td>January</td>
<td>$100</td>
</tr>
<tr>
<td>February</td>
<td>$80</td>
</tr>
</tbody>
</table>
<table>
<tbody>
<tr>
<td>January</td>
<td>$100</td>
</tr>
<tr>
<td>February</td>
<td>$80</td>
</tr>
</tbody>
</table>
<table>
<tbody>
<tr>
<td>January</td>
<td>$100</td>
</tr>
<tr>
<td>February</td>
<td>$80</td>
</tr>
</tbody>
</table>
<table>
<tbody>
<tr>
<td>January</td>
<td>$100</td>
</tr>
<tr>
<td>February</td>
<td>$80</td>
</tr>
</tbody>
</table>
答案 2 :(得分:1)
您使用的是同一个选择器,而不是tbody
。
$("tbody").each(function() {
$(this).before('<tr><td>Stuff</td></tr>');
});