JQuery hide <tr> based on <td> id

风流意气都作罢 提交于 2019-12-07 14:35:46

问题


I would like to hide some table row from my table based on the table data id, I've only found ways to hide the table row based on the table data value but that is (in my case) not the solution.

For example, lets say this is my table:

<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>

What should my javascript/JQuery look like? Fiddle: http://jsfiddle.net/twyqS/


回答1:


Take into account that ids must be unique on your page so I recommend you to use css classes instead of ids

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();

This would allow you to hide several rows if necessary.




回答2:


First of all is you're using jQuery, use it to attach your event handlers. It results in much more semantic HTML, and is a better separation of concerns.

With regard to your problem you should use the :first selector to get the first tr element, and then the hide() function:

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

Alternatively you could use the id of the tr as it is intended to be unique:

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

I would suggest familiarising yourself with the jQuery API, specifically the selectors available.




回答3:


Try this:

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



回答4:


Try this...

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

And see this...

DEMO




回答5:


ID of an element should be unique, so use class attribute instead of ID in your elements

Try

<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>

then

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

Demo: Fiddle




回答6:


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



来源:https://stackoverflow.com/questions/18233348/jquery-hide-tr-based-on-td-id

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!