HTML表头使用jQuery进行分组

时间:2015-07-01 11:02:43

标签: javascript jquery html css

我想根据相同的内容对表头进行分组。

 <table id="tblSample" border="1" >
    <tbody>
        <tr><th>Group#1</th><th>Group#1</th><th>Group#1</th><th>Group#21</th></tr>
        <tr><th>Sub-Group#1</th><th>Sub-Group#1</th><th>Sub-Group#2</th><th>Sub-Group#2</th></tr>
        <tr><td>1</td><td>2</td><td>3</td><td>4</td>   </tr>       
    </tbody>
</table>

这里我想将Group#1列合并为单列和Sub-Group#1以及。任何的想法? 我尝试了一个代码,但它没有用。 这是我的演示:http://jsfiddle.net/L3ab1edw/1/

预期产量:     ------------------------------------------------------- Group#1 | Group#2 ------------------------|--------------------------------- Sub-Group#1 | Sub-Group#2 -----------|------------|------------|--------------------- 1 |2 |3 |4

$(document).ready(function () {
    $('#tblSample').each(function () {
        var Column_number_to_Merge = 1;
          var Previous_TH = null;
        var i = 1;
        $("thead",this).find('tr').each(function () {
                var Current_th = $(this).find('th:nth-child(' + Column_number_to_Merge + ')');

            if (Previous_TH == null) {

                Previous_TH = Current_th;
                i = 1;
            } 
            else if (Current_th.text() == Previous_TH.text()) {

                Current_th.remove();

                Previous_TH.attr('colspan', i + 1);
                i = i + 1;
            } 
            else {

                Previous_TH = Current_th;
                i = 1;
            }
        });
    });
});

1 个答案:

答案 0 :(得分:1)

使用colspan

 <table id="tblSample" border="1" >
    <tbody>
        <tr><th colspan="3">Group#1</th><th>Group#21</th></tr>
        <tr><th>Sub-Group#1</th><th>Sub-Group#1</th><th>Sub-Group#2</th><th>Sub-Group#2</th></tr>
        <tr><td>1</td><td>2</td><td>3</td><td>4</td>   </tr>       
    </tbody>
</table>

我不明白为什么你需要一个jQuery来做这么简单的任务,但是你走了:

$("#tblSample")
    .find("tbody tr:first-child")
    .html('<th colspan="3">Group#1</th><th>Group#21</th>');