2015-04-05 34 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

相關問題