javascript jQuery 在一个 tr 中附加两个 tds'
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14537437/
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
jQuery append two tds' in one tr
提问by Osa
How to use jQuery to append only two tds' in a single tr ..
如何使用 jQuery 在单个 tr 中仅附加两个 tds' ..
I have a table .. I want to max how many tds per row.. something like this
我有一张桌子 .. 我想每行最多有多少 tds .. 像这样
if($("td").length) == 0){ // get the count of existing tds
$("table").append("<tr>");
}
$("table").append("<td>Something</td>");
if($("td").length) == 2){ // if it hit two tds' in this tr then close the tag
$("table").append("</tr>");
} // this is not a valid example, just trying to deliver my point
it's not a loop, it appends on click, so let's say I clicked 5times, I should get this
这不是一个循环,它在点击时附加,所以假设我点击了5次,我应该得到这个
<tr>
<td>Someting</td>
<td>Someting</td>
</tr>
<tr>
<td>Someting</td>
<td>Someting</td>
</tr>
<tr>
<td>Someting</td>
</tr>
回答by georg
Let's try this:
让我们试试这个:
var max = 2
var tr = $("table tr:last");
if(!tr.length || tr.find("td").length >= max)
$("table").append("<tr>");
$("table tr:last").append("<td>hi</td>");
回答by Felix Kling
If $("td").length
is even, create a new row, if not, append to the last row:
如果$("td").length
是偶数,则创建一个新行,如果不是,则追加到最后一行:
var $tds = $('table td');
var $target = $tds.last().parent();
if($tds.length % 2 === 0){
$target = $('<tr />').appendTo('table > tbody');
}
$target.append("<td>Something</td>");
回答by scones
$('bla').click(function() {
if ($('td').length % 2) === 0)
$('table').append('<tr />');
$('table:last').append($('<td>Something</td>'));
});