问题描述
如果display:none;
中包含的段落具有特定的类,我需要隐藏(<tr>
)整个<td>
。
示例:
<table>
<tbody>
<tr id="sample-34457" class="row-class">
<td class="cell-class"></td>
<td class="cell-class"></td>
<td class="cell-class">
<p class="hide-tr-if-class"></p>
</td>
</tr>
</tbody>
</table>
我尝试了一些使用CSS的方法,但100%的时间都无法正常工作。
我尝试过的一些jQuery:
if ($("p").hasClass(".hide-tr-if-class") ) {
$("tr#sample-*").hide();
///// OR
$(".row-class").css("display"`,"none");
};
无论哪种尝试都没有真正的运气。我的目标是使用display:none隐藏整个表行(如果该段具有该类)。如果满足条件,这将最终从列表中删除项目。
谢谢。
解决方法
使用closest
获取tr
元素的p
祖先,然后将其隐藏起来,像这样:
$("p.hide-tr-if-class") // select the 'p' elements with the class 'hide-tr-if-class',the 'if' statement is not needed here
.closest("tr") // get their closest 'tr' ancestors
.hide(); // hide them,this is equivalent to '.css( "display","none" )' but shorter and clearer
注意:如果动态添加行,则需要在生成代码后执行上述代码。
,首先,如果您使用hasClass
,则该参数将不需要.
此外,使用closest
选择最接近的父级(此处为tr
)
if ($('p').hasClass('hide-tr-if-class')) {
console.log('in here')
$('p.hide-tr-if-class').closest('tr').css('visibility','hidden');
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tbody>
<tr id="sample-34457" class="row-class">
<td class="cell-class">a</td>
<td class="cell-class">b</td>
<td class="cell-class">
<p class="hide-tr-if-class">c</p>
</td>
</tr>
<tr id="sample-34457" class="row-class">
<td class="cell-class">d</td>
<td class="cell-class">e</td>
<td class="cell-class">
<p class>f</p>
</td>
</tr>
</tbody>
</table>
,
尝试一下:
if ($("p").hasClass(".hide-tr-if-class") ) {
$(this).closest('tr').hide();
{