2012-01-08 107 views
6

假設我有一個div結構,一個文本框:如何在Jquery中創建搜索過濾器文本框?

<input id="filter" type="text" name="fname" /><br /> 
<input type="text"> 
<div id="listofstuff"> 
    <div class="anitem"> 
     <span class="item name"Dog</span> 
     <span class="itemdescruption">AboutItem1</span> 
    </div> 
    <div class="anitem"> 
     <span class="item name">Doodle Bird</span> 
     <span class="itemdescruption">AboutItem2</span> 
    </div> 
    <div class="anitem"> 
     <span class="item name">Cat</span> 
     <span class="itemdescruption">AboutItem3</span> 
    </div> 
</div> 

我想要讓這個最初..說,這表明3 anitems,我想讓它這樣,如果用戶有鍵入任何字符在搜索框中,它只會顯示與用戶輸入的條目匹配的div。

Ex。因此,如果用戶鍵入「D」,它將隱藏「項目名稱」中沒有「D」的所有其他div。 如果用戶輸入另一個字母「og」,則將顯示的唯一div是「Dog」的「項目名稱」的分區 如果用戶點擊刪除鍵刪除「g」,則兩個div將展示「狗」和「塗鴉鳥」。 如果用戶刪除它們在文本框中鍵入的所有內容,則所有的anitems都會顯示出來。

如果可能,我該如何做到這一點?我想我可能不得不使用.live(),但我真的不確定。

回答

9

你將不得不處理keyup事件(這被點擊鍵被釋放後),然後使用.filter()找到匹配的項目,顯示出他們的父母。

$("#filter").bind("keyup", function() { 
    var text = $(this).val().toLowerCase(); 
    var items = $(".item_name"); 

    //first, hide all: 
    items.parent().hide(); 

    //show only those matching user input: 
    items.filter(function() { 
     return $(this).text().toLowerCase().indexOf(text) == 0; 
    }).parent().show(); 
}); 

Live test case

0

你要處理的keyup事件,我想你可以這樣做:如果你想過濾的用戶類型

$('div').each(function() { 
    $(this).toggle($(this).children('span.itemname').text() == yourVar); 
}); 
相關問題