javascript - 是否可以在表中找到 td 的数量,然后使用 Javascript 在表标记内应用 col 宽度?

标签 javascript jquery html css

是否可以根据 td 标签的数量在 Table 标签中添加“col width”标签。如果有 2 个 td,则应添加 2 个“col width”。 & 如果有 3,则 3 "col width"。等等。

<!DOCTYPE html>
<html>

<head>
    <title>HTML colgroup Tag</title>
</head>

<body>
    <p>This example shows a colgroup that has three columns of different widths:
    </p>
    <table border="1">
        <tr>
            <th>Heading</th>
            <td>col 1</td>
            <td>col 2</td>
            <td>col 3</td>
        </tr>
    </table>
    <table border="1">
        <tr>
            <td>col 1</td>
            <td>col 2</td>
        </tr>
    </table>
</body>

</html>  

请任何人帮助我,根据td的数量添加“col group”标签。

预期输出:-

<!DOCTYPE html>
<html>

<head>
    <title>HTML colgroup Tag</title>
</head>

<body>
    <p>This example shows a colgroup that has three columns of different widths:
    </p>
    <table border="1">
        <colgroup>
            <col width="50%"></col>
            <col width="20%"></col>
            <col width="30%"></col>

        </colgroup>
        <tr>
            <th>Heading</th>
            <td>col 1</td>
            <td>col 2</td>
            <td>col 3</td>
        </tr>
    </table>

    <table border="1">
        <colgroup>
            <col width="50%"></col>
            <col width="50%"></col>

        </colgroup>
        <tr>
            <td>col 1</td>
            <td>col 2</td>
        </tr>
    </table>
</body>

</html>

最佳答案

您需要先遍历 并获取每个表的td 计数。然后根据 td 的计数创建一个 colgroup

像这样的

var output = '';
$('table').each(function() {

    var colCount = 0;
    $(this).find('tr:nth-child(1) td').each(function() { // Get the count of table columns

        if ($(this).attr('colspan')) { // if there is a <td colspan>
            colCount += +$(this).attr('colspan');
        } else {
            colCount++;
        }
        console.log($(this));
    });


    var colgroupList = '';
    for (i = 0; i < colCount; i++) { // Add a <colgroup></colgroup> for each <td>
        colgroupList += '<col width="50%"></col>';
        console.log(colgroupList);
    }
    console.log('<colgroup>' + colgroupList + '</colgroup>');

    $(this).find("tbody").prepend('<colgroup>' + colgroupList + '</colgroup>');

    output += $(this).html();

});

这是一个工作 JSFIDDLE 同样。

关于javascript - 是否可以在表中找到 td 的数量,然后使用 Javascript 在表标记内应用 col 宽度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31250844/

相关文章:

jquery - 使用jquery mask插件获取手机号码

html - <div> 有倾斜的边缘和盒子阴影

html - 使用 css3,如果不为空,则可以在 span 中使用左/右填充

javascript - 在 ajax 调用之前运行 javascript 函数

javascript - 无法让 javascript/jquery 多次正确对元素进行排序

javascript - 如何使用两个属性对对象数组进行排序,但根据条件按排序顺序有条件地分组?

javascript - 将 python 客户端服务器转换为 websocket

javascript - Firebase Cloud Storage - 使用元数据上传 -

javascript - 将 div 设置为UpperCase()

javascript - 两个选择器之间的jquery长度