gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 11:42:06 25 4
gpt4 key购买 nike

是否可以根据 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com