簡體   English   中英

Jquery隱藏不包含值的表列

[英]Jquery hide table column not containing value

如果表中包含搜索值,我會嘗試隱藏該行。

這有效:

<table class="mytable">
    <tr>
        <td>1001</td>
        <td>apples</td>
    </tr>
    <tr>
        <td>1002</td>
        <td>bananas</td>
    </tr>
</table>
<button id="mybutton">Button</button>
<button id="mybutton2">Button2</button>

這將通過隱藏所有行,然后顯示我們想要的行來工作:

$('#mybutton').click(function(){
    $('.mytable td').parent().hide();
    $('.mytable td:contains("apples")').parent().show();
});

但我已經看到使用 :not 選擇器有一個更優雅(並且可能更高效)的解決方案,但我無法讓它工作:

$('#mybutton2').click(function(){
    $('.mytable td:not(:contains("apples"))').parent().hide();
});

我怎樣才能得到這個使用的工作:沒有選擇,所以,如果一個行包含蘋果,它會被隱藏,留下所有包含蘋果的行。

JS小提琴: https : //jsfiddle.net/ryy3tvob/

因為第一個td在任何行中都不包含apple ,它會選擇所有第一個td所以它會隱藏它的父級。 所以你需要使用:contains()來表示tr

匹配的文本可以直接出現在所選元素中、該元素的任何后代中,或者它們的組合中。 與屬性值選擇器一樣,:contains() 括號內的文本可以寫成一個空詞或用引號括起來。 要選擇的文本必須具有匹配的大小寫。 (摘自https://api.jquery.com/contains-selector/

 $('#mybutton2').click(function() { $('.mytable tr:not(:contains("apples"))').hide(); });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <table class="mytable"> <tr> <td>1001</td> <td>apples</td> </tr> <tr> <td>1002</td> <td>bananas</td> </tr> </table> <button id="mybutton">Button</button> <button id="mybutton2">Button2</button>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM