我的PHP页面上有以下Javascript代码,我将表名和一个变量传递给该函数。代码的“ ALL”部分工作正常,可在页面中进行解析,并将所有CSS样式的显示描述符从“ none”翻转为“ n”或“ back”。
我遇到问题的地方是“红色”部分。应该隐藏所有包含类“ RedCell”的TD的TR,但我似乎无法使这部分按预期工作。请帮忙。
JAVASCRIPT
function expandCollapseTable(tableObj, which)
{
if (which == 'ALL')
{
var rowCount = tableObj.rows.length;
for(var row=0; row<rowCount; row++)
{
rowObj = tableObj.rows[row];
rowObj.style.display = (rowObj.style.display=='none') ? '' : 'none';
}
return;
}
if (which == 'RED')
{
$('td.RedCell').find('td.RedCell').closest('tr').style.display = 'none';
return;
}
else
{
return;
}
}
的CSS
.ResultTable td.RedCell{
background-color:#FF4747;
}
HTML按钮和示例表
<input type="button" value="Show/hide ALL" onclick="expandCollapseTable(TheTable, 'ALL')" />
<input type="button" value="Hide Red" onclick="expandCollapseTable(TheTable, 'RED')" />
<table id="TheTable" class="ResultTable" style="padding: 0px; background: #FFFFFF;" align="center">
<tr><td class="RedCell">2014-07-17 10:04</td><td>1998847</td><td>137717</td></tr>
<tr><td>2014-08-06 10:44</td><td>2009211</td><td>106345</td>
<tr><td class="RedCell">2014-07-31 16:47</td><td>2006727</td><td>138438</td>
因此,第一行和第三行将被隐藏,第二行保持可见
代码http://codepen.io/anon/pen/DrKLm的CodePen版本
最佳答案
不用从子级转到父级,而是使用jQuery :has
选择器基于后代过滤元素。
$(tableObj).find('tr:has(td.RedCell)').hide();
此外,您可能只想在所有单元格都未隐藏的情况下才将其隐藏。如果隐藏了任何内容,则需要显示这些内容,并使其余部分可见。这是一个例子...
var rows = $(tableObj).find('tr:gt(0)'); // Skips the first row
if(rows.is(':hidden')) {
// Contains elements which are hidden
rows.show();
} else {
rows.hide();
}
结果将是:
function expandCollapseTable(tableObj, which) {
var rows = $(tableObj).find('tr:gt(0)');
if(which == 'RED') {
// First snippet
rows.has('td.RedCell').hide();
} else if(which == 'ALL') {
// Second snippet
if(rows.is(':hidden')) {
rows.show();
} else {
rows.hide();
}
}
}
http://codepen.io/anon/pen/xlmcK
额外的编程功能:
第二个片段可以减少为
rows[rows.is(':hidden')?'show':'hide']();