【发布时间】:2020-02-22 07:28:26
【问题描述】:
我有多个从 wp 中的循环生成的表,并编写了 jquery 来删除具有空 td 的列,这适用于第一个表,然后在所有其他表上添加相同的列。我曾尝试使用带有 jquery 的“每个”来为每个表运行,但事实并非如此。
例子:
每个表有 1 行,列数相同 (7)。空列被隐藏,这适用于单个表。假设表 1 有 2 个可见列,表 2 有 3 个可见列。第 3 列(来自表 2)被添加到表 1,即使它是空的。
这是我的 jquery
$(document).ready(function() {
$('.man-table').each(function (table) {
//count # of columns
var numCols = $("th", table).length;
for ( var i=1; i<=numCols; i++ ) {
var empty = true;
//grab all the <td>'s of the column at i
$("td:nth-child(" + i + ")", table).each(function(index, el) {
//check if the <span> of this <td> is empty
if ( $("span", el).text() != "" ) {
empty = false;
return false; //break out of each() early
}
});
if ( empty ) {
$("td:nth-child(" + i + ")", table).hide(); //hide <td>'s
$("th:nth-child(" + i + ")", table).hide(); //hide header <th>
}
}
})
});
这是我为每个循环生成的表格
<table class='man-table'>
<thead>
<tr>
<th class='numeric'><span>inductance (r)</span></th>
<th class='numeric'><span>mount</span></th>
<th class='numeric'><span>dim (mm)</span></th>
<th class='numeric'><span>r current</span></th>
<th class='numeric'><span>impedance</span></th>
<th class='numeric'><span>capacitance</span></th>
<th class='numeric'><span>resistance</span></th>
<th class='numeric'><span>spec</span></th>
</tr>
</thead>
<tr>
<td data-title='inductance (r)' class='numeric'><span>{$ind}</span></td>
<td data-title='mount type' class='numeric'><span>{$mnt}</span></td>
<td data-title='dimensions' class='numeric'><span>{$dim}</span></td>
<td data-title='rated current' class='numeric'><span>{$rat}</span></td>
<td data-title='impedance' class='numeric'><span>{$imp}</span></td>
<td data-title='capacitance' class='numeric'><span>{$cap}</span></td>
<td data-title='resistance' class='numeric'><span>{$res}</span></td>
<td data-title='spec sheet' class='numeric'><span><a href='{$site_url}/product-spec/{$prod_pdf}' target='_blank;'><div id='spec-btn'>DOWNLOAD</div></a></span></td>
</tr>
</table>
【问题讨论】:
-
欢迎来到 Stack Overflow。这个问题不清楚。在您的示例中,您建议 Table-1 有 2 列,而 Table-2 有 3 列。在这种情况下,您想隐藏第三列?如果 Table-1 有 5 列而 Table-2 只有 2 列,你想发生什么?
-
此外,如果您想隐藏列,您可能需要将它们添加到
class以便更轻松地选择。 EG:class="col-1 numeric"那么如果您确定需要隐藏某个列,您可以轻松$(".col-3", table).hide();。 -
@Twisty 每个表都应该隐藏空列。它们应该相互独立。就像我说的那样。它可以很好地在一个表上隐藏空列...但是如果页面上有多个表,它会将具有最多列的表的列添加到所有表中。这有意义吗?
-
如何知道一列何时为空?如果表格中某一行中的一个单元格不是空的,而该列中的所有其他单元格都是空的,是否应该隐藏它?
-
@Twisty 每个表只有 1 行。因此,如果任何单元格为空,则应隐藏该列。我在上面编辑了我的文字...