[英]Hiding TR when TD contains specific class
我的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>
因此,第一行和第三行將被隱藏,第二行保持可見
CodePen版本的代碼http://codepen.io/anon/pen/DrKLm
它應該是:
$('td.RedCell', tableObj).closest('tr').hide();
要將呼叫.find()
一直在尋找另一個td.RedCell
的第一個內 。
另外,您不能將.style
屬性與jQuery對象一起使用,即用於DOM元素。 要使用jQuery隱藏某些內容,請使用.hide()
或.css("display", "none")
。
並且您需要將搜索限制在給定的tableObj
。
順便說一句,為什么不將jQuery用於ALL
選項? 整個循環可以替換為:
$("tr", tableObj).toggle();
.find說的兩個問題是查找td.RedCells的后代。 這些都沒有...
然后,使用.css設置樣式。
所以這:
$('td.RedCell').closest('tr').css('display', 'none');
而不是從子級到父級,使用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']();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.