2015-04-05 107 views
0

我有这样的一个表中的多个行,如何表格单元格拆分成使用JQuery

<table class='location'> 
<tbody> 
<tr align=center> 
    <td>Content 1</td> 
    <td>Content 2</td> 
    <td>Content 3</td> 
    <td>Content 4</td> 
    <td>Content 5</td> 
    <td>Content 6</td> 
    <td>Content 7</td> 
    <td>Content 8</td> 
</tr> 
</tbody> 
</table> 

我想重新安排使用JQuery这样的表,

<table class='location'> 
    <tbody> 
    <tr align=center> 
     <td>Content 1</td> 
     <td>Content 2</td> 
    </tr> 
    <tr align=center> 
     <td>Content 3</td> 
     <td>Content 4</td> 
    </tr> 
    <tr align=center> 
     <td>Content 5</td> 
     <td>Content 6</td> 
    </tr> 
    <tr align=center> 
     <td>Content 7</td> 
     <td>Content 8</td> 
    </tr> 
    </tbody> 
    </table> 

2细胞中的每个行。即4行,每行2个单元。

请指导我,因为我是初学者到JQuery。

由于

回答

2

下面几个jQuery方法如each()append()attr()first()last()被应用。另外isOdd功能来自较旧的Stackoverflow answer正用于检查td元素的位置。

// loop through each table td element 
$("table.location td").each(function (index) { 
    // check if it's odd or even td element based on its position 
    // element index is added 1 before checking if its position has even or odd number because index starts from 0 
    var odd = isOdd((index + 1)); 
    //if td element is position order number is odd then create new table row 
    //and append it to the table 
    if (odd) { 
     $("table.location tbody").append($("<tr>").attr("align", "center")); 
    } 
    //then append the current td element to the last table row 
    //the last table row is the most recently created row 
    $("table.location tr").last().append($(this)); 
}); 
//finally remove the first table row which is empty 
$("table.location tr").first().remove(); 

function isOdd(num) { 
    return num % 2; 
} 

Fiddle

我希望你找到答案好吗:-)

+0

感谢兄弟,让我检查一下,希望这会做... :) – Krishnan 2015-04-06 12:02:50

+0

是兄弟,逻辑/代码ü建议解决我的问题:)。但是我在建议的代码中做了一些改变,比如'$(“。location td”)。(函数(索引)if((index%2)== 0){“location tbody”)。附加($('')); } $(“。location tr”)。last()。append($(this)); });'主要是我改变** if if条件和删除第一行删除代码.....非常感谢,为整齐解释的解决方案 – Krishnan 2015-04-06 12:32:17