2014-01-22 68 views
1

所有想要隱藏tr如果第一個字母的td:nth-​​child(1)不包含字母D, atm我的代碼只是隱藏它if所有的TDS不包含字母D. HTML:隱藏tr如果其td:nth-​​child()第一個字母不包含字母

HTML

<table id="myTable"> 
    <thead> 
     <tr><th>Name</th><th>Lastname</th></tr> 
    </thead> 

    <tbody> 
     <tr><td>Zuri</td><td>Mam</td></tr> 
     <tr><td>Dima</td><td>Mam</td></tr> 
     <tr><td>Dato</td><td>Mik</td></tr> 
     <tr><td>AMD</td><td>Phen</td></tr> 
    </tbody> 
</table> 
<button id="hide">Filter by First letter D</button> 
<button id="showAll">Show All</button> 

jQuery的

$("#hide").click(function() { 
    $("#myTable tr:not(:has(th))").not(":contains(D)").hide(); 
}); 
$("#showAll").click(function() { 
    $("#myTable tr:not(:has(th))").show() 
}); 

工作JSFiddle。 請幫忙, 謝謝!

+0

得到td html(),並且只檢查第一個字符是否與 – Dibu

+0

不使用包含,它檢查整個字符串 – Dibu

回答

6

:contains()檢查字符串是否存在於內容的任何地方,你可以使用.filter()過濾tr元素

$("#hide").click(function() { 
    $("#myTable tbody tr").filter(function(){ 
     return $.trim($(this).find('td:first-child').text()).charAt(0) != 'D' 
    }).hide(); 
}); 

演示:Fiddle

+1

@downvoter是否錯過任何東西 –

+0

請更正小提琴中的代碼......這是錯誤的.. –

+0

@ShibuThomas done ..是一箇舊版本..其中的條件被否定。 –

0

嘗試這種解決方案:

$("#hide").click(function() { 
    $("#myTable tbody tr").each(function(){ 
     if($(this).find("td:first").text().substr(0,1).toUpperCase() == 'D'){ 
      $(this).hide(); 
     } 
    });  
}); 

$("#showAll").click(function() { $("#myTable tbody tr").show() }); 

http://jsfiddle.net/Pesulap/ryCm5/1/

相關問題