基于 <td> id,使用 JQuery 隐藏 <tr>。

5

我希望能够根据表格数据id隐藏一些表格行,但我只找到了根据表格数据值隐藏表格行的方法,而这(在我的情况下)并不是解决方案。

比如,假设这是我的表格:

<table id='table1' border="1">
<tr id='hideme'>
<td id='letmehide'>row 1, cell 1</td>
<td id='letmehide'>row 1, cell 2</td>
</tr>
<tr id='donthideme'>
<td id='dontletmehide'>row 2, cell 1</td>
<td id='dontletmehide'>row 2, cell 2</td>
</tr>
</table>

我的javascript/JQuery应该是什么样子的呢? 示例代码: http://jsfiddle.net/twyqS/


1
Bogers不要使用重复的ID。 - Eswara Reddy
7个回答

8

请注意,在您的页面上,id必须是唯一的,因此我建议您使用css类而不是id

HTML

<table id='table1' border="1">
<tr class='hideme'>
<td class='letmehide'>row 1, cell 1</td>
<td class='letmehide'>row 1, cell 2</td>
</tr>
<tr class='donthideme'>
<td class='dontletmehide'>row 2, cell 1</td>
<td class='dontletmehide'>row 2, cell 2</td>
</tr>
</table>

JS

$('#table1 .hideme').hide();

这将允许您在必要时隐藏多行。

好的,那是一个解决方案,但我希望JQuery可以根据td id“letmehide”隐藏第一行,如果可能的话。 - BjornBogers
建议您使用 CSS 类而不是 ID。 - Claudio Redi

2

首先,如果您正在使用jQuery,请使用它来附加事件处理程序。这会产生更具语义的HTML,并且更好地分离了关注点。

关于您的问题,您应该使用:first选择器来获取第一个tr元素,然后使用hide()函数:

$('#table1 tr:first').hide();

或者您可以使用的id,因为它旨在是唯一的:

$('#hideme').hide();

我建议熟悉jQuery API,特别是可用的选择器


1

试试这个:

$('#table1 tr[id="hideme"]').hide();//in table1 hide tr that are with attribute id="hideme"

1

元素的ID应该是唯一的, 所以在您的元素中使用class属性代替ID

尝试

<table id='table1' border="1">
    <tr class='hideme'>
        <td class='letmehide'>row 1, cell 1</td>
        <td class='letmehide'>row 1, cell 2</td>
    </tr>
    <tr class='donthideme'>
        <td class='dontletmehide'>row 2, cell 1</td>
        <td class='dontletmehide'>row 2, cell 2</td>
    </tr>
</table>

那么

$('#table1 tr:has(td.letmehide)').hide()

演示:Fiddle


1
尝试这个...
$(document).ready(function(){
    $('button').on('click', function(){
        $('#table1 tr:first').hide();
    });
});

看看这个...

DEMO


1

$("#letmehide").parent().hide();


-1

对于其他想要在多个 tr 中使用相同的 id 的人,请尝试以下方法:

$(this).closest("tr").hide();

假设传递了 this - Michael Nelles

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接