简体   繁体   中英

jQuery append two tds' in one tr

How to use jQuery to append only two tds' in a single tr ..

I have a table .. I want to max how many tds per row.. something like this

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 times, I should get this 次,我应该得到这个

<tr>
 <td>Someting</td>
 <td>Someting</td>
</tr>
<tr>
 <td>Someting</td>
 <td>Someting</td>
</tr>
<tr>
 <td>Someting</td>
</tr>

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>");

http://jsfiddle.net/5yLrE/

If $("td").length is even, create a new row, if not, append to the last row:

var $tds = $('table td');
var $target = $tds.last().parent();
if($tds.length % 2 === 0){
    $target = $('<tr />').appendTo('table > tbody');
}
$target.append("<td>Something</td>");
$('bla').click(function() {
  if ($('td').length % 2) === 0)
    $('table').append('<tr />');
  $('table:last').append($('<td>Something</td>'));
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM