我的页面中有一个HTML表格。像这样
<table class="table table-bordered table-responsive">
<thead>
<tr class="tablewhite">
<th> No</th>
<th>Options</th>
<th>Dash</th>
<th>mm</th>
<th>Inch</th>
<th>mm</th>
<th>mm</th>
</tr>
</thead>
<tbody>
<tr class="tablecontentwhite">
<td>19904408</td>
<td>S/G</td>
<td>-4</td>
<td>4.4</td>
<td>5/16"</td>
<td>7.9</td>
<td>20.0</td>
</tr>
<tr class="tablecontentblue">
<td> Material: Acidproof Stainless Steel with bronze inserted thread.</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr class="tablecontentwhite">
<td> - K=Clevis Pin Treaded w/Nut, G=Clevis Pin w/G-ring</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
&#13;
表格的最后三行可能在结构上有所不同。就像我上面显示的那样,最后两行只在第一列中有文本。如果列的第一列中只有文本,我想给它最大宽度。在这种情况下,将colspan="7"
添加到包含文本的列,并删除该行中的所有空列。期望的输出将是这样的
<table class="table table-bordered table-responsive">
<thead>
<tr class="tablewhite">
<th> No</th>
<th>Options</th>
<th>Dash</th>
<th>mm</th>
<th>Inch</th>
<th>mm</th>
<th>mm</th>
</tr>
</thead>
<tbody>
<tr class="tablecontentwhite">
<td>19904408</td>
<td>S/G</td>
<td>-4</td>
<td>4.4</td>
<td>5/16"</td>
<td>7.9</td>
<td>20.0</td>
</tr>
<tr class="tablecontentblue">
<td colspan="7"> Material: Acidproof Stainless Steel with bronze inserted thread.</td>
</tr>
<tr class="tablecontentwhite">
<td colspan="7"> - K=Clevis Pin Treaded w/Nut, G=Clevis Pin w/G-ring</td>
</tr>
</tbody>
</table>
&#13;
任何人都可以指出实现这个目标的正确方法吗?
答案 0 :(得分:2)
只是给出一个主意。你可以试试这个。适用于下一个空元素。
$('tr').each(function(index, tr) {
var previous = false;
$(tr).find('td').each(function(index1, td) {
if(td.innerText == "") {
if(previous) {
var p = $(previous);
if(!p.attr('colspan')) {
p.attr('colspan', 1);
}
p.attr('colspan', parseInt(p.attr('colspan'))+1);
$(td).remove();
}
} else {
previous = td;
}
});
});
你也可以像这样写
$('tr').each(function(index, tr) {
$(this).find('td:not(:empty)').attr('colspan', $(this).find('td:empty').length);
$(this).find('td:empty').remove();
});
对于拆分单元格长度,您可以更改第二行
$(this).find('td:not(:empty)').attr('colspan', $(this).find('td:empty').length/$(this).find('td:not(:empty)'));