javascript - 使用 jQuery 进行 HTML 表头分组

标签 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/

预期输出: -------------------------------------------- ---------- 第 1 组 |第 2 组 ----------------------|------------------------ ---------- 小组#1 |小组#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;
            }
        });
    });
});

最佳答案

使用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>');

关于javascript - 使用 jQuery 进行 HTML 表头分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31159476/

相关文章:

html - 液体布局中水平对齐的 div - 一个的背景延伸到另一个的后面

javascript - jquery - 鼠标松开后查找 2 个不同的元素

c# - 警报消息后的 Javascript 重定向

javascript - 谷歌脚本搜索匹配的ID列,然后搜索不匹配的列

javascript - 将对象传递回函数

javascript - D3.js:在转换运行时检索 x 轴信息

javascript - page.trendDescriptions = {}; 怎么样?在给定的代码段中工作?

javascript - 在光标位置拆分 div 内容

javascript - 遍历数组以将相同的值应用于其他复选框

c# - ASP.Net:文字与标签