简体   繁体   中英

Create two columns table from td in one row

I'm trying to create two columns table from the next td list via jQuery:

<table>
  <tr id="dw">
      <td>1</td>
      <td>2</td>
      <td>3</td>
      <td>4</td>
      ...
      <td>n</td>
  </tr>
</table>

I expecting something like that:

<table>
 <tr>
    <td>1</td>
    <td>2</td>
 </tr>
 <tr>
    <td>3</td>
    <td>4</td>
 </tr>
 ...
 <tr>
    <td>n-1</td>
    <td>n</td>
 </tr>
</table>

Could anyone complete my code?

$('#dw tr').each(function(){
    $('<tr>').insertAfter(this).append($('td:eq(1)',this))
})

I see one problem - You are using the selector $('#dw tr') - meaning that you are looking for an element with the ID #dw INSIDE a tr. In your example, the #dw is the actual tr. So this selector wouldn't work

why not just use $('#dw')?

$("table").append('<tr></tr>'); // generate the second row container
$("td:gt(1)").appendTo('tr+tr'); // move the 3rd-4th td to the new row

The code to create new tr , to insert current td s with index more than 1 to newly created tr and to append this new tr after existed one in table.

Fiddle

$(document).ready(function()
{
    var newTr = $('<tr>');
    $('#dw td:gt(1)').appendTo(newTr);
    newTr.insertAfter('#dw');
});

Update for updated question.

Updated fiddle

<table id="table">
  <tr id="dw">
      <td>1</td>
      <td>2</td>
      <td>3</td>
      <td>4</td>
      <td>5</td>
      <td>6</td>
      <td>7</td>
      <td>8</td>
  </tr>
</table>

Code:

$(document).ready(function()
{
    var currentTr = $('<tr>');
    var table = $('#table');
    $('#dw td').each(function(index)
    {
        currentTr.append(this);
        if (index % 2)
        {
            table.append(currentTr);
            currentTr = $('<tr>');
        }
    });
    $('#dw').remove();
});

If you have multiple rows, do like this,

$("tr").each(function() {
    $(this).find("td").filter(function() {
        return $(this).index() > 1
    }).wrapAll("<tr></tr>")

    $(this).after($(this).find("tr"));
});

Fiddle

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