2013-10-19 76 views
1

在這段代碼中,當有人輸入用戶名時,我只想顯示那一行並隱藏其他人。jquery搜索不工作

<input type="text" id="usearch"> 
<table class="table myTable"> 
    <thead> 
     <tr>   
      <th></th> 
      <th>User</th>            
     </tr> 
    </thead> 
    <tbody id="searchbody"> 
     <tr> 
      <td>Jhon</td> 
     </tr> 
     <tr> 
      <td>Jane</td> 
     </tr> 
     <tr> 
      <td>Sarah</td> 
     </tr> 
     <tr> 
      <td>Peter</td> 
     </tr> 
     <tr> 
      <td>Paul</td> 
     </tr> 
    </tbody> 
</table> 



jquery 

$(document).on('keyup','.myTable',function() { 
    var uval = $(this).val(); 
    alert(uval); 
    if(uval != '') { 
     $('.myTable tr').hide(); 
     $('.myTable tr td')each(function() { 
      if($(this).is(':contains('+uval+')')) { 
       $(this).parent('tr').show(); 
      } 
     }); 
    } 
}); 

FIDDLE:http://jsfiddle.net/nzhu6/ 這是行不通的。代碼有什麼問題?

回答

1

KeyUp事件必須連接到所述輸入元件

$('#usearch').on('keyup', function() { 
    var uval = $(this).val(); 
    var $trs = $('.myTable tbody tr'); 
    if (uval != '') { 
     $trs.hide().filter(function(){ 
      return $(this).text().toLowerCase().indexOf(uval.toLowerCase()) >= 0; 
     }).show() 
    } else { 
     $trs.show(); 
    } 
}); 

演示:Fiddle

+0

我有名稱的大寫字母。如果我想讓jquery忽略,我應該怎麼做?感謝廣告 – Ace

+0

@ user2894116嘗試更新 –