简体   繁体   中英

How to hide tr items when td is 0 in jquery?

I want to hide all of the <tr> where td 's text is 0. How can I do that? I have to mention that in reality i have more than 600 rows. But the example below is a demo. THX

<table id ="list2">
       <tbody>
            <tr>
                <td>2</td>
                <td>213</td>
                <td id ="hideRow">0</td>
            <tr>
            <tr>
                <td>vb</td>
                <td>asf</td>
                <td id ="hideRow">0</td>
            <tr>
            <tr>
                <td>cxvb</td>
                <td>xcvb</td>
                <td id ="hideRow">2</td>
            <tr>
            <tr>
                <td>cas</td>
                <td>asdf</td>
                <td id ="hideRow">45</td>
            <tr>
       </tbody>
    </table>

This is my try :| . The event is loaded by onclick event

$('#list2').find("tr td #hideRow").each(function(){
        var txt2 = $(this).text();
        if (txt2 =="0"){
            $('#list2').find("tr").each(function(){
                $(this).hide();
            });
        }
})

在此处输入图片说明

First of all do not use id for duplicate names. Try doing it like following.

<table id ="list2">
   <tbody>
        <tr>
            <td>2</td>
            <td>213</td>
            <td class="hideRow">0</td>
        <tr>
        <tr>
            <td>vb</td>
            <td>asf</td>
            <td class="hideRow">0</td>
        <tr>
        <tr>
            <td>cxvb</td>
            <td>xcvb</td>
            <td class="hideRow">2</td>
        <tr>
        <tr>
            <td>cas</td>
            <td>asdf</td>
            <td class="hideRow">45</td>
        <tr>
   </tbody>
</table>


$('#list2').find(".hideRow").each(function(){
        var txt2 = $(this).text();
        if (txt2 =="0"){
            $(this).parent().hide();
        }
})

IDs on elements need to be unique, you can't have multiple <td id="hideRow"> elements and expect things to play nicely all of the time. I'd suggest changing it to a class. Then, select all elements:

var elems = $('span.hideRow');

Filter to those whose text is 0 :

elems = elems.filter(function() {
    return $(this).text() === "0";
});

Get their parent <tr> element:

elems = elems.closest('tr');

Then, finally, hide them:

elems.hide();

That can, obviously, all be done in one line:

$('span.hideRow').filter(function() {return $(this).text() === "0";}).closest('tr').hide();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM